Mysql:从表1中选择行并测试表2中是否存在行

时间:2014-02-10 13:13:31

标签: php mysql sql

这是我的问题:

$q = $this->dao->prepare('
        SELECT wishlists.id, wishlists.title, wishlists.comment, 
               wishlists.date, users.name, users.username, 
               wishlist_following.id as wid
        FROM wishlists
            LEFT JOIN users ON wishlists.user = users.id
            LEFT JOIN wishlist_following ON wishlist_following.user_id = 25 
                AND wishlist_following.wishlist_id = wishlists.id
            WHERE users.username = :username
        ORDER BY wishlists.date DESC
        ');

其中“25”是访客的ID。我的表中有一个“wid”键,如果当前用户(id:25)没有跟随返回的wishlist,则为null。

这是我的数据库和目标:

用户(id,用户名等)

Whislists(id,title,comment,user_id) - >与用户表的多对一关系

wishlist_following(id,user_id,wishlist_id) - >与用户表的多对多关系

我的目标:我想从用户的个人资料中获取愿望清单(从URL中提取用户名),并了解当前用户(访问者)是否在此列表之后的每个心愿单。

这是最好的方式吗?

2 个答案:

答案 0 :(得分:0)

如果我正确理解你的目标,那就是:

SELECT
a.*,
CASE WHEN b.ID IS NULL THEN ‘No’ ELSE ‘Yes’ END AS Following
FROM
wishlists a
LEFT JOIN wishlist_following b ON b.wishlist_id = a.id AND b.user_id = <ID_USER_VISITOR>
WHERE a.user_id = <ID_USER_OWNER>

答案 1 :(得分:0)

此查询

SELECT w.title
FROM users u, wishlists w, wishlist_following wf
WHERE u.id = 1 -- visitor
AND w.user_id = 3 -- viewed profile
AND wf.user_id = u.id
AND wf.wishlist_id = w.id

应从id = 3

的用户个人资料中返回wishlists,后跟访问者(id 1)

好的,我弄清楚了,试试这个:

SELECT w.title, wf.id
FROM users u
LEFT JOIN wishlists w ON w.user_id = 3 -- viewed profile
LEFT JOIN wishlist_following wf ON wf.wishlist_id = w.id
WHERE u.id = 1 -- visitor

简化版:

SELECT w.title, wf.id
FROM users u, wishlists w
LEFT JOIN wishlist_following wf ON wf.wishlist_id = w.id
WHERE u.id = 1 -- visitor
AND w.user_id = 3 -- viewed profile