id title cat lang
6101 AAba 1 1
6102 AAad 4 2
6103 AAaf 4 2
6104 AAa 1 1
6105 AAtar 4 2
6106 AAao 1 1
6107 ABya 4 2
6108 ABar 4 2
6109 ACar 1 2
6110 BCad 3 1
6111 CCas 4 1
6112 DCas 4 2
6113 GCaz 2 2
6114 FCaew 2 2
6115 FCaw3 4 2
6116 FCa3 1 1
6117 FCa4 4 2
6118 FCa5 2 1
6119 FCa6 4 2 --- last id
表新闻,id是主键,title - 是title字段, cat - 有四种类型的新闻,lang - 语言代码1或2。
我想实现以下目标: 1)案例编辑新闻 - ID可用 - 例如6111,lang是1,cat是4 我想收集这些ID和标题:
6119
6117
6115
6112
6109
6105
6103
6102
是相反的语言 - lang是2,同一类别cat是4和 在给定id 6111之前和之后的4(或n)id范围内 还订购了desc
2)案例添加新闻 - id不可用,或者在php中插入后是mysql_insert_id() 相同的功能 - 最后10个id与相同的cat = 4和相反的lang = 2
到目前为止,我已经尝试过这个:
表示案例1)php片段:
$id = 6111;
$lang = 1;
$tip = 4;
$sql = "SELECT id, title
FROM pubs
WHERE id BETWEEN ".($id-4)." AND ".($id+4). " AND
tip = ".$tip." AND
lang <> ".$lang."
ORDER BY id DESC ";
但是这会在ID之前和之后获得4个ID,而不是来自我需要的ID集合。
案例2)
$sql = "SELECT id, title
FROM news
WHERE cat = 4 AND
lang <> 1
ORDER BY id DESC LIMIT 10";
这似乎有效,但可能是我错了。
有没有办法用php和mysql实现案例1? 案例2的更好方法是什么?
答案 0 :(得分:2)
鉴于你只有$id
,这种可怕的野兽是我能想到的最好的。我很确定有一个更整洁的方法,但我认为这将有效( FIXED )
$id = 6111;
$query = "
SELECT `id`, `title`
FROM `news`
WHERE `id` IN (
SELECT * FROM (
SELECT `id`
FROM `news`
WHERE `cat` = (
SELECT `cat`
FROM `news`
WHERE `id` = ".$id."
) AND `lang` != (
SELECT `lang`
FROM `news`
WHERE `id` = ".$id."
) AND `id` < ".$id."
ORDER BY `id` DESC
LIMIT 4
) `lower`
) OR `id` IN (
SELECT * FROM (
SELECT `id`
FROM `news`
WHERE `cat` = (
SELECT `cat`
FROM `news`
WHERE `id` = ".$id."
) AND `lang` != (
SELECT `lang`
FROM `news`
WHERE `id` = ".$id."
) AND `id` > ".$id."
ORDER BY `id` ASC
LIMIT 4
) `upper`
)
ORDER BY `id` DESC
";
答案 1 :(得分:-1)
这样的事可能有用:
$sql = "SELECT id, title FROM pubs
WHERE tip = ".$tip." AND lang <> ".$lang."
ORDER BY id DESC
LIMIT ".($id-4).",".($id+4);
可能有更优雅的解决方案,但这可以完成工作。