我有三个表:
users
:我需要其id
列与查询的uid
参数匹配的行的username
列matches
:我需要该行的id
,以及liked
或liker
列中的一列作为uid
。也就是说,如果查询作为参数得到的uid
是34,而liker
是34
,那么我得到liked
列,它可以是789
或其他什么pic_url
:它为一个用户有几行,但我只需要profile_pic = 1
所在的行(它将是一个(到目前为止,我已经写了以下内容:
SELECT
matches.id,
IF(matches.liker = ${uid}, matches.liked, matches.liker) AS matches.uid,
users.username,
pic_urls.url AS profilePic
FROM matches
JOIN users
ON matches.uid = users.id
JOIN pic_urls
ON users.id = pic_urls.user_id
WHERE profile_pic = 1
我不知道把过滤pic_urls
表中行的条件放在哪里,所以我只得到profile_pic
列为1
的条件(只有一个(有问题的表格是:
mysql> describe matches;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| liker | int unsigned | NO | | NULL | |
| liked | int unsigned | NO | | NULL | |
+-------+--------------+------+-----+---------+----------------+
mysql> describe users;
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| username | varchar(50) | NO | | NULL | |
| firstname | varchar(50) | NO | | NULL | |
...
mysql> describe pic_urls;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| user_id | int unsigned | NO | | NULL | |
| url | varchar(255) | NO | | NULL | |
| profile_pic | tinyint(1) | YES | | 0 | |
+-------------+--------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)
我想要:
-------+-----------+-----------+-------------------+
| id | uid | username | profpic |
+-------+-----------+-----------+------------------+
| 1 | 33 | bob | someurl |
| 5 | 22 | frank | someurl |
+-------+-----------+-----------+------------------+
其中,id
和uid
是来自matches
表的列,username
来自users
表,profpic
来自pic_urls
。
这是我想要的查询:
SELECT
matches.id,
users.id AS uid,
users.username,
pic_urls.url
FROM matches
JOIN users ON IF(matches.liker = ${uid}, matches.liked, matches.liker) = users.id
JOIN pic_urls ON IF(matches.liker = ${uid}, matches.liked, matches.liker) = pic_urls.user_id
WHERE profile_pic = 1