tags:

views:

75

answers:

2

I want to write a Mysql statement that selects all from a table(posting) where title is like $title except for the title of $title. Basically I want to display all related posting of a certain posting. I want the query to select all the postings in the table that has the title name in the title OR detail. But I don't want the posting to display in the related postings.

//pseudocode
$query="Select * From posting Where title,detail, like %$title% except $title";

how do I write the except part?

A: 

EDIT: If you want LIKE '%$title%' AND != '$title' then:

SELECT * FROM posting 
WHERE title LIKE '%$title%' AND detail LIKE '%$title%' AND title !=  '$title';

else

SELECT * FROM posting 
WHERE title LIKE '%$title%' AND detail LIKE '%$title%' AND title NOT LIKE '%$title%';

Are you sure that's correct? LIKE '%$title%' AND NOT LIKE '%$title%' is a contradiction.

Ben
It's not correct, it's like a pseudo code. I am still trying to find the correct query
ggfan
I think he wants the `title LIKE '%$title%'` and `title != '$title'`...
animuson
Yes that is right! I want to display all related posting and not the actual posting itself. Is there a way to right the code so that even if another posting has the exact same title, it would still show as a related posting?
ggfan
+2  A: 

This is the code you need, although it will be better if you have the current post id and just have something like WHERE id != " . (int)$current_post_id . "

$title = mysql_real_escape_string($title);

$sql = "
    SELECT *
    FROM posting
    WHERE
        title LIKE '%" . $title . "%' AND
        detail LIKE '%" . %title . "%' AND
        title != " . $title . "
    ";

Here is the ID version, way better :)

$title = mysql_real_escape_string($title);

$sql = "
    SELECT *
    FROM posting
    WHERE
        title LIKE '%" . $title . "%' AND
        detail LIKE '%" . %title . "%' AND
        id != " . (int)$post_id . "
    ";
Ivo Sabev
yes I do have the id(posting_id), so I'll incorporate that too! Thanks, ill try this :)
ggfan
When it is title like $title AND detail like $title, does the sql only search for where both the title and detail have $title?
ggfan
Yes it does. If you want to allow it to have `$title` in either title or description, you can put an OR between those two and put parentheses around it.
animuson
You can put (title LIKE '%" . $title . "%' OR detail LIKE '%" . %title . "%') AND id != " . (int)$post_id
Ivo Sabev
Is it a good habit to get into writing `<>` instead of `!=`, as not all SQL-variants support `!=`.
BlueRaja - Danny Pflughoeft
Bad MySQL habit, still <> is ugly to me :)
Ivo Sabev