MySQL如何使用不同的约束查询多个表?

时间:2016-09-27 16:51:12

标签: php mysql sql

如何使用不同的约束查询多个表? 例如,将结果从第一个表限制为1行,但从第二个表中获取所有结果,然后按唯一ID ASC排序这些结果。

例如,像这样:

SELECT p.entry_id AS post_id,
       p.topic AS post_topic,
       p.body AS post_body,
       r.reply AS post_reply
FROM 
#should get only one row
(SELECT entry_id, topic, body FROM entry_posts WHERE entry_id = {$id} LIMIT 1) AS p

FULL JOIN
#should get all rows with this entry_id and order them
(SELECT reply, FROM entry_replies WHERE entry_id = {$id} ORDER BY id ASC) AS r

ON p.entry_id = r.entry_id

在这种情况下,两个表都有一个名为entry_id的列,它包含相同的值。

1 个答案:

答案 0 :(得分:1)

SELECT p.entry_id AS post_id,
       p.topic AS post_topic,
       p.body AS post_body,
       r.reply AS post_reply
FROM entry_posts p
LEFT OUTER JOIN entry_replies r ON r.entry_id = p.entry_id
WHERE p.entry_id = {$id}
ORDER BY r.id