Hi im trying to make a left join on this database.
Table category:
// `category` table has 3 columns
id,business_id (FK from business),category.
Table business:
// `business` table has 12 columns
id, name, etc (all info for that business)
What I need is to filter all the business that are Restaurants and join it to the respective business ID.
Problem is that each business have multiple category and when I do a select/join the result doesnt return DISTINCT businesses.
Here is one of the query i tried:
SELECT category.category,business.*
FROM category
INNER JOIN business
ON category.business_id = business.id;
I also tried left, right joins. But my pc is either taking forever or not working.
P.S the dataset is 8.6G
![database output]: https://i.imgur.com/eF4zYOr.png
Your query looks okay, but it is lacking that you are only looking for restaurants. However, firstly, I would make sure I have an index built on category.id
create index your_index_name on your_table_name(your_column_name);
Then you can simplify your query this way:
select a.id, a.category, b.* from category a left join business b on a.business_id=b.id WHERE a.category='Restaurants';
Even with that, a table that's 8.6G is going to take time. Since you said "pc" instead of "server" it might take a long time.
Try this
SELECT *
FROM Business b
WHERE EXISTS (
SELECT 1
FROM Category
WHERE category = 'Restaurants' AND business_id = b.id
)
Related
I've got a problem with MySQL select statement.
I have a table with different Department and statuses, there are 4 statuses for every department, but for each month there are not always every single status but I would like to show it in the analytics graph that there is '0'.
I have a problem with select statement that it shows only existing statuses ( of course :D ).
Is it possible to create temporary table with all of the Departments , Statuses and amount of statuses as 0, then update it by values from other select?
Select statement and screen how it looks in perfect situation, and how it looks in bad situation :
SELECT utd.Departament,uts.statusDef as statusoforder,Count(uts.statusDef) as Ilosc_Statusow
FROM ur_tasks_details utd
INNER JOIN ur_tasks_status uts on utd.StatusOfOrder = uts.statusNR
WHERE month = 'Sierpien'
GROUP BY uts.statusDef,utd.Departament
Perfect scenario, now bad scenario :
I've tried with "union" statements but i don't know if there is a possibility to take only "the highest value" for every department.
example :
I've also heard about
With CTE tables, but I don't really get how to use it. Would love to get some tips on it!
Thanks for your help.
Use a cross join to generate the rows you want. Then use a left join and aggregation to bring in the data:
select d.Departament, uts.statusDef as statusoforder,
Count(uts.statusDef) as Ilosc_Statusow
from (select distinct utd.Departament
from ur_tasks_details utd
) d cross join
ur_tasks_status uts left join
ur_tasks_details utd
on utd.Departament = d.Departament and
utd.StatusOfOrder = uts.statusNR and
utd.month = 'Sierpien'
group by uts.statusDef, d.Departament;
The first subquery should be your source of all the departments.
I also suspect that month is in the details table, so that should be part of the on clause.
I have three tables that I want to combine.
I have the following query to run:
DROP TABLE
IF EXISTS testgiver.smart_curmonth_downs;
CREATE TABLE testgiver.smart_curmonth_downs
SELECT
ldap_karen.uid,
ldap_karen.supemail,
ldap_karen.regionname,
smart_curmonth_downs_raw.username,
smart_curmonth_downs_raw.email,
smart_curmonth_downs_raw.publisher,
smart_curmonth_downs_raw.itemtitle,
smart_items.`Owner`
FROM
smart_curmonth_downs_raw
INNER JOIN ldap_karen ON smart_curmonth_downs_raw.username = ldap_karen.uid
INNER JOIN smart_items ON smart_curmonth_downs_raw.itemtitle = smart_items.Title
I want to know how to create the joins while maintaining a one to one relationship at all times with rows in table smart_curmonth_downs_raw.
For instance if there is not a uid in ldap_karen I have issues. And then the last issue I have found is that our CMS is allowing for duplicate itemtitle. So if I run my query I am getting a lot more rows because it is creating a row for each itemtitle. For example would there be a way to only catch the last itemtitle that is in smart_items. I would just really like to maintain the same number of rows - and I have no control over the integrity issues of the other tables.
The smart_curmonth_downs_raw table is the raw download information (download stats), the karen table adds unique user information, and the smart_items table adds unique items (download) info. They are all important. If a user made a download but is knocked off the karen table I would like to see NULLs for the user info and if there is more than one item in smart_items that has the same name then I would like to see just the item with the highest ID.
It sounds like relationship between smart_curmonth_downs_raw and ldap_karen is optional, which means you want to use a LEFT JOIN which all the rows in the first table, and, if the right table does not exists, use NULL as the right table's column values.
In terms of the last item in the smart_items table, you could use this query.
SELECT title, MAX(id) AS max_id
FROM smart_items
GROUP BY title;
Combining that query with the other logic, try this query as a solution.
SELECT COALESCE(ldap_karen.uid, 'Unknown') AS uid,
COALESCE(ldap_karen.supemail, 'Unknown') AS supemail,
COALESCE(ldap_karen.regionname, 'Unknown') AS regionname,
smart_curmonth_downs_raw.username,
smart_curmonth_downs_raw.email,
smart_curmonth_downs_raw.publisher,
smart_curmonth_downs_raw.itemtitle,
smart_items.`Owner`
FROM smart_curmonth_downs_raw
INNER JOIN (SELECT title, MAX(id) AS max_id
FROM smart_items
GROUP BY title) AS most_recent
ON smart_curmonth_downs_raw.itemtitle = most_recent.Title;
INNER JOIN smart_items
ON most_recent.max_id = smart_items.id
LEFT JOIN ldap_karen
ON smart_curmonth_downs_raw.username = ldap_karen.uid;
I have three tables:
POP(country, year, pop)
FOOD(country, year, food)
INCOME(country, year, income)
I am trying to create a view such as:
V(country, year, pop, food, income)
This is my code so far. I don't think its correct:
CREATE VIEW V AS
(SELECT * FROM POP
UNION
SELECT * FROM FOOD
UNION
SELECT * FROM INCOME);
One issue is, a country that is present in POP may not be present in FOOD. Same goes for year. A year that is present in POP may not be present in FOOD. So, I keep thinking that the above code will not work.
Union is not what you want. You want to use joins to create single rows. It's a little unclear what constitutes a unique row in your tables and how they really relate to each other and it's also unclear if one table will have rows for every country in every year. But I think this will work:
CREATE VIEW V AS (
SELECT i.country,i.year,p.pop,f.food,i.income FROM
INCOME i
LEFT JOIN
POP p
ON
i.country=p.country
LEFT JOIN
Food f
ON
i.country=f.country
WHERE
i.year=p.year
AND
i.year=f.year
);
The left (outer) join will return rows from the first table even if there are no matches in the second. I've written this assuming you would have a row for every country for every year in the income table. If you don't things get a bit hairy as MySQL does not have built in support for FULL OUTER JOINs last I checked. There are ways to simulate it, and they would involve unions. This article goes into some depth on the subject: http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/
This works too and you dont have to use join or anything:
DROP VIEW IF EXISTS yourview;
CREATE VIEW yourview AS
SELECT table1.column1,
table2.column2
FROM
table1, table2
WHERE table1.column1 = table2.column1;
Thanks for the help. This is what I ended up doing in order to make it work.
CREATE VIEW V AS
SELECT *
FROM ((POP NATURAL FULL OUTER JOIN FOOD)
NATURAL FULL OUTER JOIN INCOME);
Are you using MySQL or PostgreSQL?
You want to use JOIN syntax, not UNION. For example, using INNER JOIN:
CREATE VIEW V AS
SELECT POP.country, POP.year, POP.pop, FOOD.food, INCOME.income
FROM POP
INNER JOIN FOOD ON (POP.country=FOOD.country) AND (POP.year=FOOD.year)
INNER JOIN INCOME ON (POP.country=INCOME.country) AND (POP.year=INCOME.year)
However, this will only show results when each country and year are present in all three tables. If this is not what you want, look into left outer joins (using the same link above).
I want to get some data out of my database that is similar to a receipt you get at the supermarket (just an example which suits kinda good to my real situation).
For example you get the 2 (always only 2) products 1 and 3. These products are stored in a seperated product database.
Your shopping result is stored in one database containing all the details like time, location and so on AND in 2 columns (product_1, and product_2). Again this shopping situation is only a comparison to my real situation so I know that this would not be a good database structure for a shopping list.
So now I would like to get the Whole receipt but instead of printing the product IDs I would like to have the Name and for example the price on it.
If I had only one product I would use this query:
SELECT `list`.`time`, `list`.`location`, `prod`.`prod_name`, `prod`.`prod_price`
FROM `shopping_list` `list`, `products` `prod`
WHERE `list`.`product_1` = `prod`.`prod_id`
But since I have two products I cannot just go on with
AND `list`.`product_2` = `prod`.`prod_id`
But how do you achive what I would like to have?
Thank you very much,
Phil
You'll need to join to the product table twice
e.g.
SELECT
`list`.`time`,
`list`.`location`,
`prod1`.`prod_name` `prod_name1`,
`prod1`.`prod_price` `prod_price1` ,
`prod2`.`prod_name` `prod_name2`,
`prod2`.`prod_price` `prod_price2`
FROM `shopping_list` `list`
INNER JOIN `products` `prod1`
ON `list`.`product_1` = `prod1`.`prod_id`
INNER JOIN `products` `prod2`
ON `list`.`product_2` = `prod2`.`prod_id`
I'm not sure what your business rules are so you may need to convert the second INNER JOIN to a LEFT JOIN if they need to always select two products.
i don't know your exact situation but usually field names like product_1 and product_2 indicate bad database design. however if you really need that you need to join the products table twice.
select
*
from
list l
, product p1
, product p2
where
l.product_1 = p1.product_id
and l.product_2 = p2.product_id
(this is oracle syntax but i think it will work also in mysql).
hth.
The previous answers work well if you can parse out the two lines from 1 database result row. If you want two lines from the database you could do a UNION query:
SELECT `list`.`time`, `list`.`location`, `prod`.`prod_name`, `prod`.`prod_price`
FROM `shopping_list` `list`, `products` `prod`
WHERE `list`.`product_1` = `prod`.`prod_id`
UNION
SELECT `list`.`time`, `list`.`location`, `prod`.`prod_name`, `prod`.`prod_price`
FROM `shopping_list` `list`, `products` `prod`
WHERE `list`.`product_2` = `prod`.`prod_id`
I need to gather posts from two mysql tables that have different columns and provide a WHERE clause to each set of tables. I appreciate the help, thanks in advance.
This is what I have tried...
SELECT
blabbing.id,
blabbing.mem_id,
blabbing.the_blab,
blabbing.blab_date,
blabbing.blab_type,
blabbing.device,
blabbing.fromid,
team_blabbing.team_id
FROM
blabbing
LEFT OUTER JOIN
team_blabbing
ON team_blabbing.id = blabbing.id
WHERE
team_id IN ($team_array) ||
mem_id='$id' ||
fromid='$logOptions_id'
ORDER BY
blab_date DESC
LIMIT 20
I know that this is messy, but i'll admit, I am no mysql veteran. I'm a beginner at best... Any suggestions?
You could put the where-clauses in subqueries:
select
*
from
(select * from ... where ...) as alias1 -- this is a subquery
left outer join
(select * from ... where ...) as alias2 -- this is also a subquery
on
....
order by
....
Note that you can't use subqueries like this in a view definition.
You could also combine the where-clauses, as in your example. Use table aliases to distinguish between columns of different tables (it's a good idea to use aliases even when you don't have to, just because it makes things easier to read). Example:
select
*
from
<table> as alias1
left outer join
<othertable> as alias2
on
....
where
alias1.id = ... and alias2.id = ... -- aliases distinguish between ids!!
order by
....
Two suggestions for you since a relative newbie in SQL. Use "aliases" for your tables to help reduce SuperLongTableNameReferencesForColumns, and always qualify the column names in a query. It can help your life go easier, and anyone AFTER you to better know which columns come from what table, especially if same column name in different tables. Prevents ambiguity in the query. Your left join, I think, from the sample, may be ambigous, but confirm the join of B.ID to TB.ID? Typically a "Team_ID" would appear once in a teams table, and each blabbing entry could have the "Team_ID" that such posting was from, in addition to its OWN "ID" for the blabbing table's unique key indicator.
SELECT
B.id,
B.mem_id,
B.the_blab,
B.blab_date,
B.blab_type,
B.device,
B.fromid,
TB.team_id
FROM
blabbing B
LEFT JOIN team_blabbing TB
ON B.ID = TB.ID
WHERE
TB.Team_ID IN ( you can't do a direct $team_array here )
OR B.mem_id = SomeParameter
OR b.FromID = AnotherParameter
ORDER BY
B.blab_date DESC
LIMIT 20
Where you were trying the $team_array, you would have to build out the full list as expected, such as
TB.Team_ID IN ( 1, 4, 18, 23, 58 )
Also, not logical "||" or, but SQL "OR"
EDIT -- per your comment
This could be done in a variety of ways, such as dynamic SQL building and executing, calling multiple times, once for each ID and merging the results, or additionally, by doing a join to yet another temp table that gets cleaned out say... daily.
If you have another table such as "TeamJoins", and it has say... 3 columns: a date, a sessionid and team_id, you could daily purge anything from a day old of queries, and/or keep clearing each time a new query by the same session ID (as it appears coming from PHP). Have two indexes, one on the date (to simplify any daily purging), and second on (sessionID, team_id) for the join.
Then, loop through to do inserts into the "TempJoins" table with the simple elements identified.
THEN, instead of a hard-coded list IN, you could change that part to
...
FROM
blabbing B
LEFT JOIN team_blabbing TB
ON B.ID = TB.ID
LEFT JOIN TeamJoins TJ
on TB.Team_ID = TJ.Team_ID
WHERE
TB.Team_ID IN NOT NULL
OR B.mem_id ... rest of query
What I ended up doing is;
I added an extra column to my blabbing table called team_id and set it to null as well as another field in my team_blabbing table called mem_id
Then I changed the insert script to also insert a value to the mem_id in team_blabbing.
After doing this I did a simple UNION ALL in the query:
SELECT
*
FROM
blabbing
WHERE
mem_id='$id' OR
fromid='$logOptions_id'
UNION ALL
SELECT
*
FROM
team_blabbing
WHERE
team_id
IN
($team_array)
ORDER BY
blab_date DESC
LIMIT 20
I am open to any thought on what I did. Try not to be too harsh though:) Thanks again for all the info.