Multiple Where clause using same columns SQL - php

I have table like this :
user_id field_id value
1 1 toto
2 1 tata
2 2 tata Job
user_id is the id of my users, field_id is the id of the information about the user (name, job, etc.) and value is the value.
I use a searchBar in HTML/PHP with 2 fields : 'name' and 'job'.
When someone search user using this two fields I need to retrieve the user id that matches these two conditions.
My question is :
How to get in SQL all user_id that match with two condition in one like this:
(field_id=1 and value=tata) AND (field_id=2 and value=tata's Job)
Thank you and have a good day !

SQL executes the WHERE logic for each row, not for the entire set. And fields cannot have more than one value. So, you need to use an OR statement instead of an AND to capture both conditions:
Select User_Id, Field_Id, Value
From YourTable
Where (field_id = 1 And value = 'tata')
Or (field_id = 2 And value = 'tata Job')

One method uses aggregation:
select user_id
from t
where (field_id = 1 and value = 'tata') or (field_id = 2 and value = 'tata''s Job')
group by user_id
having count(distinct field_id) = 2;

You can use IN statement, for example: Your table name is users
SELECT user_id
FROM users
WHERE field_id IN (1,2) AND `value` IN ('tata','tata\'s Job')

Related

How to fetch value of primary key?

I have an SQL table where there are three columns: id, name, and group. I want to get the value of group from below example:
Id = 1
Name = abc
Group = 1
I need an SQL query from which I can get value abc on fetching group=1.
You should use something like this:
SELECT Name
FROM table_name_here
WHERE table_name_here.Group = 1
You can do if you want to strict filter your request using operator AND/OR.
SELECT id, name, group FROM TABLENAME
WHERE id = 1 AND name = "abc" AND group = 1;

update row without deleting previous values in mysql

One of my table has a field user_ids and the value of the field like 2,3
group_id| user_ids
--------|------------
1 | 2,3
--------|------------
2 | 5,8
I want to update the field without deleting the current value. For ex. If I need to add 5 for group_id id 1, then 2,3 should be like 2,3,5
I m using this query:
UPDATE users_group SET user_ids = CONCAT( SUBSTRING( user_ids, 1, CHAR_LENGTH( user_ids ) -1 ) , ',5' ) WHERE group_id =1
But it is deleting previous value with comma.
group_id| user_ids
--------|------------
1 | ,5
--------|------------
2 | 5,8
can anyone suggest the right way for this?
Can you not just concatenate it on, rather than trying to split it up first?
UPDATE users_group
SET user_ids = CONCAT_WS(',', user_ids, '5' )
WHERE group_id =1
But this does suggest a badly normalised database design. Generally a comma separated list should instead be stored as rows on another table (ie, one row per value in the list) as suggested by Mark Baker.
EDIT - If you want to only have a single copy of any id in each user_ids field, irrespective of how many times you try to insert it, and you want to be able to add multiple ids at once:-
UPDATE users_group a
INNER JOIN
(
SELECT 3 AS an_id
UNION
SELECT 4
) b
ON FIND_IN_SET(b.an_id, a.user_ids) = 0
SET a.user_ids = CONCAT_WS(',', a.user_ids, b.an_id )
WHERE a.group_id =1
EDIT again - if you have a table of users containing the ids then you can select the ids from that where the id is one of those you want to add.
Something like this.
UPDATE users_group a
INNER JOIN
(
SELECT id
FROM users
WHERE id IN (3, 4)
) b
ON FIND_IN_SET(b.id, a.user_ids) = 0
SET a.user_ids = CONCAT_WS(',', a.user_ids, b.id )
WHERE a.group_id =1
update table1 set name = concat(name, ', ', 5) WHERE group_id =1
Please try this query. It may be useful for you.
UPDATE users_group SET user_ids = CONCAT( user_ids , ',5' ) WHERE group_id =1
Try the below query:
UPDATE users_group
SET user_ids = CONCAT( user_ids , ',5' )
WHERE group_id =1

Mysql select from table by comparing value in another table

I have two tables first and second.
first Table:
ID NAME ADDRESS
1 test testing address
2 test1 testing address
3 test2 testing address
4 test3 testing address
second Table:
T_ID Partner_id date
1 2 12345678
3 4 32164584
If input T_id is given. Then corresponding Partner_id is taken and it is compared with the ID from first table and corresponding row should be selected.
Can you please tell me.
In php I can write this with two queries but I want it to be in a single query.
Queries in php:
$q=mysqli_query($conn, "SELECT Partner_id from second where T_ID=1");
$qa=mysqli_fetch_array($q);
$w=mysqli_query($conn, "SELECT * from first where ID=$qa[0]");
But, how to combine this two statements?
The specified result can be returned using a query with a join operation.
SELECT f.*
FROM first f
JOIN second s
ON s.Partner_id = f.ID
WHERE s.T_ID=1
Note that there is a potential for this to return more rows that the original, if the first query returns more than one row. (That is, we don't assume that T_ID is unique in second, or that every row with a given T_ID value will have identical values for Partner_id.)
There are other query patterns that will return an equivalent result, but the join operation is the normative pattern.
try to use union ,see this this link
where The SQL UNION operator combines the result of two or more SELECT statements.
SELECT * FROM first WHERE ID IN( SELECT Parent_id FROM second WHERE T_ID = 1 )
or
SELECT * FROM first WHERE ID = ( SELECT Parent_id FROM second WHERE T_ID = 1 )
SELECT * FORM first_table AS f
JOIN second_table AS s
ON s.parent_id =f.id
WHERE s.T_ID = $id

trying to output the correct value from SQL query from comparing a different table

I'm very new with SQL and need assistance on how I can accomplish this task using the correct query.
I have 2 tables that I need to use. Table "TB1" has:
id Name
1 bob
2 blow
3 joe
table "TB2" has:
compid property
1 bob
2 blow
I am trying to get which compid is missing in "TB2" and insert it from "TB1"
the query I am doing is:
SELECT id, name from TB1, TB2 where id <> compid
what I get is 2 ouputs of Id 1, and 2, and 3 outputs from id 3. by using php:
for($i=0;$i <= mysql_num_rows($comp)-1; $i++)
{
echo mysql_result($comp, $i, 0)."<br>";
}
and I expected the ouput 3 but instead got this:
1
1
2
2
3
3
3
I understand its comparing all the rows within the table but is there a way to achieve what I am looking for?
Thanks for your time.
You are performing an implicit Cartesian JOIN which results in every row against every other row. You need to specify what attribute JOINs the two tables.
Using implicit syntax (not recommended):
SELECT id, name
FROM TB1, TB2
WHERE id <> compid
AND TB1.Name = TB2.property <-- Column join
Using explicit syntax:
SELECT id, name
FROM TB1
JOIN TB2
ON TB2.property = TB1.Name <-- Column join
WHERE id <> compid
To accomplish your goal you would need something along the lines of:
SELECT TB1.id, TB1.name
FROM TB1
LEFT JOIN TB2
ON TB2.property = TB1.Name
WHERE TB2.compid IS NULL
See it in action
It's best practice to always alias the columns you select to prevent ambiguity.
To select it you can do:
SELECT *
FROM TB1
WHERE id NOT IN (
SELECT compid
FROM TB2
);

Select a row where one column is min

I'm writing a simple URL rotator for a client and they want the URLs to rotate according to the oldest one that was previously displayed.
My columns are very simple:
url_id | company_id | url | last_clicked
I want to fetch a single row where the company_id is passed in and the last_clicked is the minimum of all records matching the company_id.
It should also select a random url_id if all last_clicked values are empty.
I assume this can be accomplished with a GROUP BY and HAVING but I can't seem to get the query to return anything.
I have this:
$last = $this->db->fetchOne ("SELECT url_id FROM
{$this->prefix}urls GROUP BY company_id HAVING MIN(last_clicked)
WHERE company_id='$company'");
This will fetch the row where last_clicked is smallest, or at random if they are all NULL:
SELECT url_id FROM urls
WHERE company_id = $company
ORDER BY last_clicked, RANDOM() LIMIT 1;
An index based on company_id and last_clicked would greatly help:
CREATE INDEX urls_ndx ON urls(company_id, last_clicked);
SELECT url_id FROM
TABLE
WHERE company_id='$company'
AND last_clicked = ( SELECT MIN(last_clicked)
FROM TABLE WHERE company_id='$company' )

Categories