insert data into table that results from a JOIN SELECT QUERY? - mysql

How can I insert data to a table that results from a JOIN SELECT query
I'd like to insert into b.URL the value ="ok" from the result of the query below
SELECT
a.ESN,
b.URL,
a.Status,
a.GroupID,
a.RouteID
FROM STx a
LEFT JOIN Routes b
ON a.RouteID = b.RouteID
WHERE a.GroupID = 39
AND a.Status = "Tested"
order by a.ESN;

I think maybe this is what you need:
UPDATE Routes b
SET URL = 'ok'
WHERE EXISTS
(SELECT * FROM STx a
WHERE a.GroupID = 39
AND a.Status = 'Tested'
AND a.RouteID = b.RouteID)
This will set the desired URL values to 'ok'.

You just prefix it with INSERT INTO table (columns). If you are trying to find b.URL values in your SELECT, then add a filter.

insert into desire_table (col1,col2,col3,...) SELECT
a.ESN,
b.URL,
a.Status,
a.GroupID,
a.RouteID
FROM STx a
LEFT JOIN Routes b
ON a.RouteID = b.RouteID
WHERE a.GroupID = 39
AND a.Status = "Tested"
order by a.ESN;
Remember that the output columns has to be matched in order to be able to sit in the new table, orders mather it means your first selected column goes to col1 and second one goes to col2 so you have to match the col1,col2,and so on with your select output

Related

How can I display the values excluded by the Where clause?

I'm trying to figure out how to to display all those values that are excluded from this WHERE clause instead of those that are chosen by:
$pdo = $service->pdo;
$sql = "SELECT a.id, a.name, a.surname, a.job, b.start_date, b.end_date
FROM table1 a
INNER JOIN table2 b on b.id = a.id
WHERE a.job = '{$job}'
AND
STR_TO_DATE(b.`start_date`, '%d-%m-%Y') = '{$date}'
GROUP BY a.id ";
return $pdo->query($sql)->fetchAll(PDO::FETCH_OBJ);
What this query returns are values that match "work title" first and then values that exist in that date in the table 2. What I'm trying to show are all the other values based on the "work title" excluding those values that exist for that specific date. Basically I need to figure out for example how to know who is free in a specific date based on this query.
Thank you for your help
You can modify your query and set the inverse where clause like this, you get the rows that don't match 'work title' OR (this is important) the rows that don't match the date requeriment in table2:
$pdo = $service->pdo;
$sql = "SELECT a.id, a.name, a.surname, a.job, b.start_date, b.end_date
FROM table1 a
INNER JOIN table2 b on b.id = a.id
WHERE a.job <> '{$job}'
OR
STR_TO_DATE(b.`start_date`, '%d-%m-%Y') <> '{$date}'
GROUP BY a.id ";
return $pdo->query($sql)->fetchAll(PDO::FETCH_OBJ);
EDIT
After reading your comments, i see that you don´t need the roes that your query has dircarded, you need the rows that match the first requeriment and don't match the second one. So you would need it this way:
$pdo = $service->pdo;
$sql = "SELECT a.id, a.name, a.surname, a.job, b.start_date, b.end_date
FROM table1 a
INNER JOIN table2 b on b.id = a.id
WHERE a.job = '{$job}'
AND
STR_TO_DATE(b.`start_date`, '%d-%m-%Y') <> '{$date}'
GROUP BY a.id ";
return $pdo->query($sql)->fetchAll(PDO::FETCH_OBJ);

How can I accomplish the following in SQL?

I have two tables.
table_a:
id | data_x | data_y
--------------------
1 person joe
2 person bob
3 amount 200
4 addres philville
tableB:
map_id | table_a_id
-------------------
7 1
7 3
7 4
8 4
8 2
The result I want is the map_id if it has an entry in table_a for both data_x = 'person' and data_y = '200'
So with the above table B, the result should be
map_id
------
7
How can I write that query in SQL?
This situation is a perfect fit for an unusual SQL operator: INTERSECT. It is a very declarative, efficient and elegant solution for this problem.
SELECT Map.map_id
FROM Table_B AS Map JOIN Table_A AS Person ON (Person.id = Map.table_a_id) AND (Person.data_x = 'person')
INTERSECT
SELECT Map.map_id
FROM Table_B AS Map JOIN Table_A AS Amount ON (Amount.id = Map.table_a_id) AND (Amount.data_y = '200')
Formally what you are asking for is exactly the intersection of two disjoint sets: the set of map id's that are persons and the set of map id's that have a value of 200.
Please note the INTERSECT operator does not exists in MySQL, but it does in almost all advanced relational DBMS, including PostgreSQL.
This is less elegant than the INTERSECT solution #Malta posted, but it works with the limited capabilities of MySQL as well:
SELECT b1.map_id
FROM table_a a1
JOIN tableb b1 ON a1.id = b1.table_a_id AND a1.data_x = 'person'
JOIN tableb b2 ON b2.map_id = b1.map_id AND b2.table_a_id <> b1.table_a_id
JOIN table_a a2 ON a2.id = b2.table_a_id AND a2.data_y = '200';
SQL Fiddle for MySQL.
SQL Fiddle for Postgres.
Based on your input, the following should get you started using MySQL:
SELECT
map_id
FROM TableB
JOIN Table_A
ON TableB.table_a_id = Table_A.id
AND
((Table_A.data_x = 'person')
OR
(Table_A.data_y = '200')
)
GROUP BY map_id
HAVING COUNT(table_a_id) = 2
;
See it in action: SQL Fiddle.
Update
As Erwin Brandstetter made explicit: If the data can't be trusted to be inherently consistent (along the lines of your inquiry), one option is:
SELECT map_id FROM (
SELECT map_id, 'data_x' t
FROM TableB B JOIN Table_A A ON B.table_a_id = A.id AND A.data_x = 'person'
UNION
SELECT map_id, 'data_y'
FROM TableB B JOIN Table_A A ON B.table_a_id = A.id AND A.data_y = '200'
) T
GROUP BY map_id
HAVING COUNT(DISTINCT t) = 2
;
This should ensure "at least one each". (Alternatives have been suggested by others.) To get "exactly one each", you could try
SELECT map_id FROM (
SELECT map_id, 'data_x' t, data_y
FROM TableB B JOIN Table_A A ON B.table_a_id = A.id AND A.data_x = 'person'
UNION
SELECT map_id, 'data_y', data_y
FROM TableB B JOIN Table_A A ON B.table_a_id = A.id AND A.data_y = '200'
) T
GROUP BY map_id
HAVING COUNT(DISTINCT t) = 2 AND COUNT(DISTINCT data_y) = 2
;
See it in action (with additional test data): SQL Fiddle.
And it works in PostgreSQL as well: SQL Fiddle
Please comment if and as this requires adjustment / further detail.
Join the 2 tables, group by map_id, use conditional counting with either count() or sum(), and filter in having clause (I use mysql syntax below):
select map_id,
sum(
case
when a.data_x='person' or a.data_y='200' then 1
else 0
end
) as matches
from a
inner join b on a.id=b.a_id
group by b.map_id
having matches=2
The above query assumes that you cannot have more than one record for any map_id where data_x is person or data_y is 200. If this assumption is incorrect, then you need to use either exists subqueries or 2 derived tables.
Sounds like you want a standard INNER JOIN.
But I do beg to differ on your result:
map_id if it has an entry in table_a for both data_x = 'person' and data_y = '200'
There is not a record in your data set that has both 'person' and data_y = '200' and therefore no mp_id can be returned
Here is a typical INNER JOIN relating to your narrative.
SELECT DISTINCT
b.map_id
FROM
TableA a
INNER JOIN TableB b
ON a.id = b.table_a_id
WHERE
a.data_x = 'person'
AND a.data_y = '200'
If more than one map_id exists with data_x = 'person' and data_y = '200' then you will get multiple results but only 1 row per map_id
If you want the map_id(s) for records with data_x = 'person' or data_y = '200' then switch the and in the where statement to or and you will receive map_id 7 & 8.
SELECT DISTINCT
b.map_id
FROM
TableA a
INNER JOIN TableB b
ON a.id = b.table_a_id
WHERE
a.data_x = 'person'
OR a.data_y = '200'
Note this encompasses (7,1)(8,2) because 1 & 2 both have data_x = 'person' and then (7,3) because 3 has data_y = '200' therefore it would return map_id 7 & 8.
select map_id from
table_b b
left outer join table_a a1 on (b.table_a_id = a1.id and a1.data_x = 'person')
left outer join table_a a2 on (b.table_a_id = a2.id and a2.data_y = '200')
group by map_id
having count(a1.id) > 0 and count(a2.id) > 0
Lets do it simple:
SELECT * FROM
(
SELECT map_id
FROM table_a a1
inner join TableB b1 ON a1.id = b1.table_a_id
where a1.data_x = 'person'
) as p
inner join
(
SELECT map_id
FROM table_a a1
inner join TableB b1 ON a1.id = b1.table_a_id
where a1.data_y = '200'
) as q
on p.map_id = q.map_id
You may replace SELECT * FROM with SELECT p.map_id FROM.
You may add more sub-set-joins to have more conditions.
sql-fiddle

Select Insert and Update in One Query MySql

I am trying to update one table from 3 tables which is working fine, but i want to update a table from 3 after i insert data in 4th table, here what i am doing
INSERT INTO relation_table(cid,pid,liid,lnid,lgid,l_key)
SELECT a.cid,
a.pid,
b.liid,
c.lnid,
d.lgid,
md5(CONCAT(a.cid, a.pid, a.lurl, c.lnid, d.lang))
FROM links a
INNER JOIN links_table b
ON a.lurl = b.lurl
INNER JOIN lname_table c
ON a.lname = c.lname
INNER JOIN lang_table d
ON a.lang = d.lang
where a.checked != "3" limit 2;
update links SET checked='3'
WHERE lid=a.lid
Last statement is not working for update
Please help ;)
Try this:
UPDATE links a
INNER JOIN links_table b ON a.lurl = b.lurl
INNER JOIN lname_table c ON a.lname = c.lname
INNER JOIN lang_table d ON a.lang = d.lang
SET a.checked='3'
WHERE a.checked != '3' LIMIT 2;

How can I update data into a table resulting from a query in MYSQL

I query this table here
SELECT
a.ESN,
b.URL,
a.Status,
a.GroupID,
a.RouteID
FROM STx a
LEFT JOIN Routes b
ON a.RouteID = b.RouteID
WHERE a.GroupID = 39
AND a.Status = "Provisioned"
order by a.ESN;
now from the result set of this , I'd like to modify url of table Routes to test for all the rows in the url column from the result of the first query .. how can I do that in a query ?
update Routes set url = 'test'
where id in (
select b.id
from Stx a left join routes b on a.routeid = b.routeid
where a.groupid = 39 and a.status = 'Provisioned'
);
If I understand your question correctly, you want to update the URL column to 'Test' for all the results that you get from your original query.
UPDATE Routes
SET URL = 'Test'
FROM STx AS A
LEFT JOIN Routes AS B
ON a.RouteID = b.RouteID
WHERE a.GroupID = 39 AND a.Status = 'Provisioned'

MySQL: Query and join two tables

I have two tables that I believe I want to JOIN. I'm very new to this and am not completely sure…
The first table is called venues with the variables id, slug, name, etc. The second table is venue_terms with the variables id, option, venue, value. The matching variables are obviously venues.id and venue_terms.venue.
What I want to do is query venue_terms for matching values and then SELECT * FROM venues that match.
I've been working with the following query, but haven't been able to get it to work. I know INTERSECT isn't the solution, but I'm nut sure which JOIN I should use.
SELECT venue
FROM venue_terms
WHERE `option` = '1' AND `value` = '10'
INTERSECT
SELECT venue
FROM venue_terms
WHERE `option` = '2' AND `value` = '4';
I want to match those venue_terms.venue to the venues table. Can someone point me in the right direction?
UPDATE: To clarify, I'm trying to search multiple option/value combinations that ultimately have the same venue.id's. Basically, I want to able to find all of the venues where (option = 1 and value = 4) AND (option = 2 and value = 10) AND etc… where all of these are true.
You want to find venues that match conditions in two rows in table venue_terms. This can be accomplished by various methods. The most usual is by joining that table twice (another would be by a grouping query).
Here's the first way. Join twice to the venue_terms table:
SELECT v.id --- whatever columns you need
, v.slug --- from the venues table
, v.name
FROM venues AS v
INNER JOIN venue_terms AS vt1
ON vt1.venue = v.id
INNER JOIN venue_terms AS vt2
ON vt2.venue = v.id
WHERE ( vt1.option = 1 AND vt1.value = 10 )
AND ( vt2.option = 2 AND vt2.value = 4 ) ;
If you have 3 conditions, join thrice. If you have 10 conditions, join 10 times. It would be good for the efficiency of the query to have a compound index on (option, value, venue) in the terms table.
try this
SELECT venue.*, venue_terms.*
FROM venue
INNER JOIN venue_terms ON venue.id = venue_terms.venue
WHERE venue_terms.option IN ( 1 ,2)
AND venue_terms.value IN (10,4)
GROUP BY venue.id
How about this?
SELECT t1.*, t2.*
FROM venue t1 JOIN venue_terms t2
ON t1.id = t2.venue
WHERE (t2.option = 1 AND t2.value = 10)
NOTE: I believe option and value are of type INT.
If they are of type varchar then change above query to
SELECT t1.*, t2.*
FROM venue t1 JOIN venue_terms t2
ON t1.id = t2.venue
WHERE (t2.option = '1' AND t2.value = '10')
Update 1
As per your new requirement, you will just need to add that condition with OR option as shown below.
SELECT t1.*, t2.*
FROM venue t1 JOIN venue_terms t2
ON t1.id = t2.venue
WHERE
(t2.option = 1 AND t2.value = 10)
OR
(t2.option = 3 AND t2.value = 14)
This will join the two tables and print out the venues which matches the attributes (option, value) in venue_terms:
SELECT v.* FROM venue v, venue_terms vt
WHERE v.id = vt.venue
AND vt.option = 1
AND vt.value = 10