MYSQL - 'SELECT'和'AS只能制作一列..如何让它们更多?

时间:2012-02-10 14:23:11

标签: mysql select

我有这样的疑问:

SELECT ( SELECT name FROM text WHERE id = 100 ) as name, x, y, w, h FROM pictures WHERE id_obj = 'example' AND picture_type = 20 ORDER BY id DESC LIMIT 1

只要图片表中有符合条件的行,它就可以正常工作。不幸的是(并且很明显为什么)当没有picture_type = 20和id_obj ='example'时它会产生空结果,尽管'text'表中有id = 100的行。

问题是:无论“图片”表中是否存在图片类型和id_obj,如何从“文本”表中选择名称?

我发现了这样的查询,但我不喜欢它(它太复杂了,看起来很糟糕)。

SELECT 
( SELECT name FROM text WHERE id = 100 ) as name, 
(SELECT x FROM pictures WHERE id_obj = 'example' AND picture_type = 20) as x, 
(SELECT y FROM pictures WHERE id_obj = 'example' AND picture_type = 20) as y, 
(SELECT w FROM pictures WHERE id_obj = 'example' AND picture_type = 20) as w, 
(SELECT h FROM pictures WHERE id_obj = 'example' AND picture_type = 20) as h, 
(SELECT id FROM pictures WHERE id_obj = 'example' AND picture_type = 20) as id 
ORDER BY id DESC LIMIT 1

我可以让它更干净吗? 提前谢谢。

1 个答案:

答案 0 :(得分:3)

尝试使用左连接,应该可以正常工作:

SELECT t.name, p.x, p.y, p.w, p.h FROM text t
LEFT JOIN pictures p ON p.id_obj = 'example' AND p.picture_type = 20
WHERE t.id = 100