我有3个表 - 用户,期刊,期刊。我使用选择的标签从3个表中选择数据。
$sqltheme="SELECT users.id as uid, users.name, users.surname, users.avatar, journals.id, journals.author_id, journals.title, journals.text, journals.create_date, journaltags.name as jname FROM users
INNER JOIN journals ON users.id=journals.author_id
INNER JOIN journaltags ON journaltags.journal_id = journals.id WHERE journals.create_date LIKE ? AND journals.author_id=? AND (".$expression.") ORDER BY journals.id DESC LIMIT 10";
$stmtheme=$conn->prepare($sqltheme);
$stmtheme->execute($array);
但是如果一个期刊的两个标签相同,那么它将被选择两次相同的期刊。我怎样才能制作DISTINCT journals.id。我试过GROUP BY journals.id
,但没有帮助。
答案 0 :(得分:0)
如果我理解正确,您的问题是journaltags表可能有一行或多行,其中包含重复的journal_id
和name
列值,对吧?
您只需在单词distinct
后面的select语句中添加SELECT
子句:
SELECT DISTINCT users.id as uid, users.name, users.surname, users.avatar, journals.id, journals.author_id, journals.title, journals.text, journals.create_date, journaltags.name as jname FROM users
INNER JOIN journals ON users.id=journals.author_id
INNER JOIN journaltags ON journaltags.journal_id = journals.id WHERE journals.create_date LIKE ? AND journals.author_id=? AND (".$expression.") ORDER BY journals.id DESC LIMIT 10
您的GROUP BY journals.id
无效的原因是因为您还需要将其他列包含在分组中。添加distinct
本质上是撰写group by [all selected columns]