MYSQL按第二个表排序

时间:2012-09-07 23:22:09

标签: php mysql

我有一个名为properties的表,我希望获得此表中与“hold = 1”匹配的所有记录,但是额外的表包含不同语言的属性名称我需要获取英语或者如果不存在语言标记默认

表格属性:

pid     hold

property_translations:

pid     lang_id     pname     description     isDefault

我通常使用联盟

获得语言
(select pname from property_translations where lang_id='en' and pid=$pid)
union
(select pname from property_translations where isDefault='Yes' and pid=$pid)
limit 1

4 个答案:

答案 0 :(得分:1)

SELECT p.pid, t.pname FROM properties p LEFT OUTER JOIN translations t ON p.pid = t.pid
    WHERE p.hold=1 AND t.isDefault='Yes' AND NOT EXISTS
    ( SELECT * FROM translations ti WHERE ti.pid = p.pid AND ti.lang_id='en')
    UNION SELECT p.pid, t.pname FROM properties p 
    LEFT OUTER JOIN translations t ON p.pid = t.pid
    WHERE p.hold=1 AND t.lang_id='en';

答案 1 :(得分:0)

尝试:

   SELECT pt.pname
     FROM property_translations AS pt
LEFT JOIN properties AS p ON p.pid = pt.pid
    WHERE pt.pid = $pid
      AND p.hold = 1
      AND pt.lang_id='en'
      AND isDefault='Yes'

答案 2 :(得分:0)

如果您的select获得了所需的结果,并且您只想按hold=1过滤它们,则只需加入第一个表:

(select pname from property_translations t
              join properties p on (t.pid=p.pid and p.hold = 1)
              where lang_id='en' and pid=$pid)
union
(select pname from property_translations t
              join properties p on (t.pid=p.pid and p.hold = 1)
              where isDefault='Yes' and pid=$pid
              and not exists (select 1 from property_translations t2
                              where t2.pid=t.pid and t2.lang_id='en' and t2.isDefault='Yes'))

请注意,我没有检查原始select的有效性,只是说明如何在第二张表中添加支票。

答案 3 :(得分:0)

SELECT p.pid pid, pname
from properties p
JOIN (SELECT t1.pid tpid, IFNULL(t2.pname, t1.pname) pname
      FROM translations t1
      LEFT OUTER JOIN translations t2
      ON t1.pid = t2.pid
      AND t2.lang_id = 'en'
      WHERE t1.isDefault = 'Yes') t
ON p.pid = t.pid
WHERE p.hold = 1