使用带有LIKE子句的引用列

时间:2014-01-11 18:30:36

标签: php mysql sql

我有SELECT个查询,其子查询的别名为nativePhraseStringforeignPhraseString。我想使用别名与搜索字符串进行比较。

SELECT item.itemID, item.groupID, item.itemType,

(SELECT GROUP_CONCAT(word.string SEPARATOR " ") FROM phrase, phrase_word, word, item AS subItem 
WHERE word.wordID=phrase_word.wordID 
AND phrase_word.phraseID=phrase.phraseID 
AND phrase.phraseID= subItem.nativePhraseID
AND subItem.itemID=item.itemID
ORDER BY phrase_word.wordIndex) AS nativePhraseString,

(SELECT GROUP_CONCAT(word.string SEPARATOR " ") FROM phrase, phrase_word, word, item AS subItem 
WHERE word.wordID=phrase_word.wordID 
AND phrase_word.phraseID=phrase.phraseID 
AND phrase.phraseID= subItem.foreignPhraseID
AND subItem.itemID=item.itemID
ORDER BY phrase_word.wordIndex) AS foreignPhraseString

FROM item
WHERE item.groupID=:groupID
AND nativePhraseString LIKE :search
OR foreignPhraseString LIKE :search;

但是,nativePhraseStringforeignPhraseString都无法识别。如何在LIKE条款中使用它们?

BTW我正在使用PDO来执行此查询。查询的其余部分已经过测试。

1 个答案:

答案 0 :(得分:3)

一种方法:

SELECT * FROM
(
    SELECT item.itemID, item.groupID, item.itemType,

    (SELECT GROUP_CONCAT(word.string SEPARATOR " ") 
     FROM phrase, phrase_word, word, item AS subItem 
    WHERE word.wordID=phrase_word.wordID 
    AND phrase_word.phraseID=phrase.phraseID 
    AND phrase.phraseID= subItem.nativePhraseID
    AND subItem.itemID=item.itemID
    ORDER BY phrase_word.wordIndex) AS nativePhraseString,

    (SELECT GROUP_CONCAT(word.string SEPARATOR " ") FROM phrase, 
                   phrase_word, word, item AS subItem 
    WHERE word.wordID=phrase_word.wordID 
    AND phrase_word.phraseID=phrase.phraseID 
    AND phrase.phraseID= subItem.foreignPhraseID
    AND subItem.itemID=item.itemID
    ORDER BY phrase_word.wordIndex) AS foreignPhraseString

    FROM item
) xx
    WHERE xx.groupID=:groupID
    AND (xx.nativePhraseString LIKE :search
         OR xx.foreignPhraseString LIKE :search);

我在WHERE子句中添加了额外的括号,以确保维护您的操作顺序。