SELECT statement across multiple tables - mysql

First off, I am not an SQL coder.
I am trying to select information from 2 different tables in the same database.
Table 1 is called trans and has 3 columns:
CustNumb, DoT, Amount
Table 2 is called cust and has multiple columns:
CustNumb, Name, Address, City, State, Zip, Phone
The SELECT statement that I'm trying to write will pull data from both tables.
SELECT trans.CustNumb
, cust.Name
, cust.City
, cust.State
, trans.DoT
, trans.Amount
, cust.Phone
,
FROM trans
, cust
WHERE CustNumb LIKE 1234
I THINK I need to use a JOIN statement, but I'm sure what kind of a JOIN or the proper syntax.
Thanks for your help!

You do need a JOIN. In fact, you should simply never write , in the FROM clause.
The JOIN you need would appear to be on the common column between the two tables:
SELECT t.CustNumb, c.Name, c.City, c.State, t.DoT, t.Amount, c.Phone
FROM trans t JOIN
cust c
ON t.CustNumb = c.CustNumb
WHERE c.CustNumb = 1234;
In addition, you should understand that LIKE is a string function and 1234 is not a string. Presumably, you just want equality -- so use =.

Related

How to Merge Two Select Query in Mysql

I have below table structure in my users table where user and driver are saved with a unique id and separated with user_type column. user ratings are being saved in rider_avg_ratings column and driver ratings are being saved in driver_avg_ratings column.
when a user submit a request it is being saved in requesttable with both userid and nearby driver id. now I have to return both driver ratings and user ratings from users table in a single query.Problem is when I join request.userid=users.id it is returning rider_avg_ratings to get the driver_avg_ratings i need to join users.id=request.driver_id how can I get both user and driver ratings from a single query
From above two table by joinning request.user_id=users.id I need to return driver_avg_ratings=4.38 and rider_avg_ratings=1.25
SELECT r.user_id as userId, u.rider_avg_ratings as ratings
FROM user as u
INNER JOIN request as r on u.id = r.user_id
UNION
SELECT r1.driver_id as userId, u1.driver_avg_ratings as ratings
FROM user as u1
INNER JOIN request as r1 on u1.id = r1.driver_id
This query will fetch the desired result.
Your union query should produce a The used SELECT statements have a different number of columns error. You need to figure out why your code isn't checking for errors and make it do so. Also, if this is the entire statement, the parentheses around it don't belong.
You need to make the two unioned selects return the same number of parameters. Note that as in the second select's select columns will be ignored and result column names will come from the first select only. Minimally, to make the query run, you would need to add ,NULL,NULL,... to your second select, but it seems likely you want more information to be able to identify which user the driver_avg_ratings is for, like the id, name, etc the first query is returning.
It's often helpful when processing the results to add something indicating which select a row came from, too, e.g. SELECT "pending_request_users" AS type, ... UNION ALL SELECT "all_users_avg_rating", ....
Note that the different SELECTs unioned together return entire rows. If your only goal is to add driver ratings to the rows already returned, you don't want a union, you may just want to add:
SELECT ..., driver.driver_avg_ratings
FROM user u
...
INNER JOIN user AS driver ON driver.id=req.driver_id
(or left join if there may not be a driver_id). But it's hard to tell for sure if that's what you want. Provide sample data and your desired results from it. In any case, do make your code detect errors properly.
for example:
Department
1 A
2 B
3 A
4 C
5 B
6 D
7 E
8 F
You could do something like
SELECT
1 AS Deptnumber
, Dept
FROM tbl_students
WHERE Dept IN ('A', 'B', 'C')
UNION
SELECT
2 AS DeptNumber
, Dept
FROM tbl_students
WHERE Dept IN ('D', 'E')
UNION
SELECT
3 AS Deptnumber
, Dept
FROM tbl_students
WHERE Dept IN ('F')

JOIN Statement For Multiple Tables Not Working

I just started learning SQL last night. I'm having trouble displaying data using multiple JOIN statements. The tables I have are:
Table: CUSTOMER
Contains CustomerID, Country, Last Name
Table: TRANS
Contains CustomerID, TransactionID, DateSold, WorkID
Table: WORK
Contains WorkID, Title, Description
Here's my query:
Select CUSTOMER.LastName, CUSTOMER.CustomerID, WORK.WorkID,
Description, Title
FROM CUSTOMER JOIN TRANS
ON CUSTOMER.CustomerID = TRANS.CustomerID
JOIN WORK
ON TRANS.WorkID = WORK.WorkID
WHERE DateSold = '11/17/2014'
GROUP BY CUSTOMER.CustomerID, TRANS.CustomerID, CUSTOMER.LastName,
WORK.WorkID, Title, DateSold, Description
Note that in the select statement, I've deliberately left out a few items that appear in the GROUP BY statement, just for the sake of this post. (Their inclusion in the SELECT statement doesn't cause program to execute properly.)
All that appears is the GROUP BY statement, but no actual data. Please help me with what I'm doing wrong. Thank you.
Use the STR_TO_DATE function in mysql to convert the date string.
WHERE DateSole = STR_TO_DATE('11/17/2014', '%m/%d/%Y')
You can join one table with two different table but you have to start from the common table.
For how you wrote the query you are saying to join CUSTOMER first with TRANS and then with WORK but the conditions are wrong for this situation (and it is not what you want to do).
Select CUSTOMER.LastName, CUSTOMER.CustomerID, WORK.WorkID,
Description, Title
FROM TRANS JOIN CUSTOMER
ON CUSTOMER.CustomerID = TRANS.CustomerID
JOIN WORK
ON TRANS.WorkID = WORK.WorkID
WHERE DateSold = '11/17/2014'
GROUP BY CUSTOMER.CustomerID, TRANS.CustomerID, CUSTOMER.LastName,
WORK.WorkID, Title, DateSold, Description
It is TRANS that you join first with CUSTOMER and then with WORK.

Joining tables in MySQL and requesting data from second table only

I'm trying to join 2 tables where I need to show only 3 columns from the second one where another column is used as a comparison.
For example:
Table one is called employee: it has a column called user_id and some other columns
Table two is called people: it has a column called user_id which included some of the employees user_ids
The columns I want to select are all from table people! (firstname, lastname, email)
I tried the following but something going wrong:
SELECT userid, firstname, lastname, email
FROM people
JOIN employee
WHERE people.userid = employee.userid;
I'm not sure what am I doing wrong, could you please help me correct it?
You can try this query:
SELECT
p.userid,
p.firstname,
p.lastname,
p.email
FROM
people as p,
employee as emp
WHERE
p.userid = emp.userid
Looking at your script, it looks like you'll run into ambiguous columns in at least your userid. You want to explicitly tell SQL where the column comes from like in your WHERE clause if there are columns sharing the same name between the two tables.
SELECT
userid, -- AMBIGUOUS
firstname,
lastname,
email
FROM people
JOIN employee
WHERE people.userid = employee.userid;
Example solution:
SELECT
people.userid,
people.firstname,
people.lastname,
people.email
FROM people
JOIN employee
WHERE people.userid = employee.userid;
For this issue you can use this query
let suppose that I have a users table where a user have zero to one profile picture
I need the user (Name,LastName,BirthDate) for users who have no profile picture
I can use this query
select *
from user c
where NOT EXISTS (
select 1
from photo p
where p.id = c.photo_id
)
in this where you can use any field between this two table
removing the not will result on the users who have a profile picture
hope this help you
you can search for SEMI JOIN and ANTI JOIN for more informations
i think this query will solve your problem
insert into table1 (clmn_1,clmn_2,clmn_3) SELECT clmn_1,clmn_2,clmn_3 FROM table2 where id = value

SQL Comment Grouping

I have two table in MySQL
Table 1: List of ID's
--Just a single column list of ID's
Table 2: Groups
--Group Titles
--Members **
Now the member field is basically a comments field where all the ID's that are part of that group are listed. So for instance one whole field of members looks like this:
"ID003|ID004|ID005|ID006|ID007|ID008|... Etc."
There they can be up to 500+ listed in the field.
What I would like to do is to run a query and find out which ID's appear in only three or less groups.
I've been taking cracks at it, but honestly I'm totally lost. Any ideas?
Edit; I misunderstood the question the first time, so I'm changing my answer.
SELECT l.id
FROM List_of_ids AS l
JOIN Groups AS g ON CONCAT('|', g.members, '|') LIKE CONCAT('%|', l.id, '|%')
GROUP BY l.id
HAVING COUNT(*) <= 3
This is bound to perform very poorly, because it forces a table-scan of both tables. If you have 500 id's and 500 groups, it must run 250000 comparisons.
You should really consider if storing a symbol-separated list is the right way to do this. See my answer to Is storing a delimited list in a database column really that bad?
The proper way to design such a relationship is to create a third table that maps id's to groups:
CREATE TABLE GroupsIds (
memberid INT,
groupid INT,
PRIMARY KEY (memberid, groupid)
);
With this table, it would be much more efficient by using an index for the join:
SELECT l.id
FROM List_of_ids AS l
JOIN GroupsIds AS gi ON gi.memberid = l.id
GROUP BY l.id
HAVING COUNT(*) <= 3
select * from
(
select ID,
(
select count(*)
From Groups
where LOCATE(concat('ID', a.id, '|'), concat(Members, '|'))>0
) as groupcount
from ListIDTable as a
) as q
where groupcount <= 3

MySQL: how to determine which rows in tables A and B are referenced by rows in table C in linear time?

I am working with a poorly designed database that I am not at liberty to restructure. In this database, there are three tables (let's call them 'companiesA', 'companiesB', and 'items') that are involved in a query that I need to optimize. 'companiesA' and 'companiesB' describe companies in the same way in that the column values are the same, but they represent two different groups of companies and have different column names. Essentially, the ID and company name columns are 'aID' and 'aName' in 'companiesA', and 'idB' and 'nameB' in 'companiesB'. 'items' contains a column, 'companyID', that contains a foreign key value from one of the two company tables.
The query I need to optimize gets a page's worth of company IDs and names from the union of the two tables, sorted by the names column, with an added column that states whether the row's company has any items associated with it. This query can also filter by the company names if the user requests it in the front-end. In its current state, I think it runs in THETA(companies * items) time, which is prohibitively slow:
select
a.aID as companyID,
a.aName as companyName,
(select
count(companyID)
from
items
where
companyID = a.aID
) as items
from
companiesA as a
where
a.aName like '%<string>%'
union
select
b.idB as companyID,
b.nameB as companyName,
(select
count(companyID)
from
items
where
companyID = b.idB
) as items
from
companiesB as b
where
b.nameB like '%<string>%'
order by
companyName ASC
limit
[optional_starting_index, ] 50;
It is not important that the items column contain the actual counts as this query returns (it was the only way I could figure out to cleanly return a value regarding the entire 'items' table). I suppose that I can count myself fortunate that with 1500 companies and 9000 items, this algorithm only takes seven seconds.
If I were writing this in another language in which I had access to the tables myself, I could easily write this in O(companies + items) time, but I am finding it difficult to figure out how to do so in MySQL. Is it possible to do this, preferably without stored functions or procedures? I CAN add them if necessary, but I have had a hard time adding them through phpMyAdmin now that the server's host only allows that interface to access the database by GUI.
In this solution, I took the daring assumption that the company names in each of the tables are unique by using Union All. If they are not, then you can switch back to Union but you'll get the performance hit of making the list unique. Basically, I'm eliminating your need for correlated subqueries to return the counts by using derived tables.
Select Companies.CompanyID, Companies.CompanyName
, Coalesce(ItemTotals.ItemCount,0) As ItemCount
From (
Select a.aID As CompanyID, a.aName As CompanyName
From companiesA As a
Where a.aName Like '%<string>%'
Union All
Select b.IDB, b.nameB
From companiesB As b
Where b.bName Like '%<string>%'
) As Companies
Left Join (
Select companyID, Count(*) As ItemCount
From items
Group By companyID
) As ItemTotals
On ItemTotals.companyID = Companies.CompanyID
Order By Company.CompanyName
Here is another variant. This one is similar to your original except that I replaced the correlated subqueries with two Group By queries. As before, if the names and IDs between the two tables are mutually exclusive, you can use Union All otherwise you will need to use Union.
Select Z.CompanyId, Z.CompanyName, Z.ItemCount
From (
Select A.companyID, A.aName As CompanyName
, Count(I.CompanyID) As ItemCount
From companiesA As A
Left Join items As I
On I.CompanyId = A.CompanyId
Where A.aName Like '%<string>%'
Group By A.companyID, A.aName
Union All
Select B.companyID, B.bName, Count(I.CompanyID)
From companiesB As B
Left Join items As I
On I.CompanyId = B.CompanyId
Where B.bName Like '%<string>%'
Group By B.companyID, B.bName
) As Z
Order By Z.CompanyName