简体   繁体   English

只选择一列不同的mysql

[英]select only one column distinct mysql

I have 3 tables - users, journals, journaltags. 我有3个表 - 用户,期刊,journaltags。 I select data from 3 tables using chosen tags. 我使用选择的标签从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);

But if two tags is the same for one journal then it is selected the same journal two times. 但是,如果一个期刊的两个标签相同,则两次选择同一个期刊。 How can I make DISTINCT journals.id. 我怎样才能制作DISTINCT journals.id。 I tried GROUP BY journals.id but it didnt help. 我试过GROUP BY journals.id但它没有帮助。

If I understand correctly, your problem is that the journaltags table may have one or more rows with a duplicated journal_id and name column value, right? 如果我理解正确,你的问题是journaltags表可能有一行或多行,其中包含重复的journal_idname列值,对吧? You can simply add a distinct clause to your select statement, after the word SELECT : 您可以在SELECT语句后面的select语句中添加一个distinct子句:

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

The reason that your GROUP BY journals.id did not work, is because you had other columns that needed to be included in the grouping as well. 您的GROUP BY journals.id不起作用的原因是因为您还有其他列需要包含在分组中。 Adding distinct is essentially a short way of writing group by [all selected columns] 添加distinct本质上是一种group by [all selected columns]编写group by [all selected columns]的简短方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM