我在用户生成内容的可视化显示上使用d3js。使用标准的三个表从数据库中提取正在显示的数据:条目,条目标记,条目标记查找表。我的d3js代码需要JSON输出才能工作。我正确编码了PHP-to-JSON输出,但我很难搞清楚我需要写什么查询才能获取正确的ID。
条目表(create_thought)
id | email | thought_title
标签表(ideas_tags)
tag_id | tag_name
查找表(ideas_tagged)
tagged_id | tag_id | thought_id
PHP-to-JSON代码(正常运行)
$titlequery = "
SELECT `thought_title` FROM `create_thought`
";
//THE BELOW QUERY IS INCORRECT
$tagquery = "
SELECT `tag_id` AS `source`, `thought_id` AS `target` FROM `thoughts_tagged`
";
$query1 = mysql_query($titlequery);
if ( ! $query1 ) {
echo mysql_error();
die;
}
$query2 = mysql_query($tagquery);
if ( ! $query2 ) {
echo mysql_error();
die;
}
$datatitle = array();
for ($x = 0; $x < mysql_num_rows($query1); $x++) {
$datatitle[] = mysql_fetch_assoc($query1);
}
$datatag = array();
for ($y = 0; $y < mysql_num_rows($query2); $y++) {
$datatag[] = mysql_fetch_assoc($query2);
}
echo '{
"nodes":' . json_encode($datatitle) . ',"links":' . json_encode($datatag) . '}';
输出如下:
{ "nodes":[{"thought_title":"Title1"},{"thought_title":"Title2"}],"links":[{"source":"1","target":"8"},{"source":"2","target":"8"},{"source":"2","target":"17"}]}
我的问题是链接(源/目标)都不正确。我需要源是think_id,目标是所有带有匹配tag_ids的thought_ids。我试图摆弄How to filter SQL results in a has-many-through relation的一些解决方案,但它们不是我需要的。
下面是我得到的最接近的,但我不知道如何用源和目标格式化它;它只是用一个匹配的标签(55)拉出think_id。
SELECT id
FROM create_thought
WHERE EXISTS (SELECT * FROM thoughts_tagged
WHERE thought_id = id AND tag_id = 55)
编辑:想出来了,这似乎更接近,但格式不正确。我需要基于匹配标签列出的think_ids,但没有别的。
SELECT DISTINCT t1.*
FROM thoughts_tagged t1
INNER JOIN thoughts_tagged t2
ON t1.tag_id = t2.tag_id AND t1.thought_id <> t2.thought_id
感谢任何帮助!
答案 0 :(得分:0)
以下是我所知道的开发人员能够提出的答案。它完美无缺。 :)
SELECT DISTINCT
t1.thought_id as source,
t2.thought_id as target
FROM thoughts_tagged t1
INNER JOIN
thoughts_tagged t2
ON t1.tag_id = t2.tag_id AND t1.thought_id <> t2.thought_id