MYySQL is the Table Relationship wrong? - mysql

I'm very new in Databases and more specific in MYSQL. I use xampp + MySQL Workbench.
I make 3 tables using MySQL Workbench:
- tbStores with fields StoreID(PK-INT-AI), StoreName
- tbProducts with fields ProductID(PK-INT-AI), ProductName
- tbProductDetails with fields ProductDetailID(PK-INT-AI), Price, ProductID(FK), StoreID(FK)
*PK=Primary Key
*INT=Numeric Type Attributes
*AI=Auto Increments
In case you don’t understand the Relationships above:
1 to many From tbStores(StoreID) To tbProductDetails (StoreID)
1 to many From tbProducts(ProductID) To tbProductDetails (ProductID)
I add values to the fields:
- tbStores=> StoreName=> Store 1
- tbProducts=> ProductName=> Product 1, Product 2
- tbProductDetails=> Price=> 50, 30
- tbProductDetails=> ProductID=> 1, 2
- tbProductDetails=> StoreID=> 1, 1
To the Query:
SELECT tbStores.StoreName, tbProductDetails.Price, tbProducts.ProductName
FROM tbStores, tbProductDetails, tbProducts
Where ProductName = 'Product 1';
The Problem:
Query will return this
Store 1, 50, Product 1
Store 1, 30, Product 1
Is giving me Same Product with 2 different Prices.
What I was expecting to take was this :
Store 1, 50, Product 1
What am I doing wrong? I believe it has to do with relationships but I can't figure it out. Thanks

You need to join the tables together (specify how they are related) in the query, the query should look something like this:
SELECT tbStores.StoreName, tbProductDetails.Price, tbProducts.ProductName
FROM tbProductDetails
JOIN tbStores ON tbStores.StoreID = tbProductDetails.StoreID
JOIN tbProducts ON tbProducts.ProductID = tbProductDetails.ProductID
WHERE tbProducts.ProductName = 'Product 1';
If you want all products you have to remove the where clause. Note that I took the liberty of changing your implicit joins in the from clause to explicit joins using the join keyword.
Sample SQL Fiddle
Sample output:
| STORENAME | PRICE | PRODUCTNAME |
|-----------|-------|-------------|
| Store1 | 50 | Product1 |

What you want is to use JOIN combined with ON
SELECT StoreName, Price, Product Name
FROM tblStores
JOIN tblProduct ON tblStores.StoreID = tblProducts.StoreID
JOIN tblProductDetails ON tblProduct.ProductID = tblProductDetails.ProductID
WHERE ProductName = 'Product 1'
You may consider GROUP BY to identify the specific stores.

Related

MySQL query to gather incorrectly stored data

I have recently taken over a email campaign project and need to generate a report for the customer. However the data has been stored very strangely.
Basically the client wants a report of the subscribers first name and last name that have subscribed to a emailing list.
Example table data.
------------------------------------------------------------
id | owner_id | list_id | field_id | email_address | value
------------------------------------------------------------
1 10 1 137 me#example.com John
2 10 1 138 me#example.com Doe
So as you can see, John Doe has subscribed to mailing list 1, and field_id 137 is his first name and field_id 138 is his last name.
The client is looking for a export with the users first name and last name all is one field.
I tred the following sql query
SELECT value
FROM Table_A AS child
INNER JOIN Table_A AS parent
ON parent.email_address = child.email_address
WHERE child.owner_id = '10'
But unfortunately the query gives me the results in many rows but not appending the first name and last name into one field,
If anyone can provide some assistance that would be awesome.
Thanks.
SELECT
concat( parent.value,' ',child.value)name
FROM mytable AS child
left JOIN mytable AS parent
ON parent.email_address = child.email_address
WHERE child.owner_id = '10'
and parent.field_id=137 and child.field_id=138
Check at-http://sqlfiddle.com/#!9/199b4b/45
I think you have to use a variable to put in there everything you have to and then select the variable with the desired name of yours.
For example:
DECLARE #yourvariable VARCHAR(MAX)
SELECT #yourvariable = COALESCE(#yourvariable + " ") + value
FROM table_A
WHERE owner_id = 10
SELECT #yourvariable as FullName
Try that, it might help.
You can try this code(column name equals value in your original DB):
select a.name
from
table_a a inner join table_a b
on a.email_address = b.email_address and a.field_id <> b.field_id
where a.owner_id=10
order by a.field_id
Here is the example link:
http://sqlfiddle.com/#!9/5fbdf6/25/0
As per assumptions, first name has the field id 137 and last name has the field id 138.
You can try the following query to get the desired result.
SELECT CONCAT(SUBSTRING_INDEX(GROUP_CONCAT(`value`),",",1)," ",SUBSTRING_INDEX(GROUP_CONCAT(`value`),",",-1)) AS client_name
FROM Table_A
WHERE owner_id = 10
AND field_id IN (137, 138)
GROUP BY email_address;

Dynamic Table Joining Based on Another Table Column Value?

I'm trying to figure out if there is a simple way to dynamically load a 2nd table based on the column value of the first table with mysql
Servers (Table 1):
ID | Game | Title
Servers_1 (Table 2, option 1):
server_id (links to servers.id) | game_version | players | plugins
Servers_2 (Table 2, option 2):
server_id (links to servers.id) | game_version | players | mods | game_map
Servers_etc. (Table 2, option etc.)
Trying to figure out how to do something like
left_join servers_[servers.game] on servers.id = servers_[servers.game].server_id
So it would grab the value of servers.game and use that to finish the table name. If this is not possible, then is a case statement possible such as:
Left_Join
if ( servers.game == 1 ) 'servers_1'
elseif ( servers.game == 2 ) 'servers_2'
elseif ( servers.game == 3 ) 'servers_3'
One option would be to LEFT JOIN each of the tables and use a CASE statement to return the appropriate data.
Something like this should help get you started:
SELECT S.Id, S.Game, S.Title,
CASE S.Game
WHEN 1 THEN S1.game_version
WHEN 2 THEN S2.game_version
END game_version,
...
FROM Servers S
LEFT JOIN Servers_1 S1 ON S.id = S1.Server_Id AND S.Game = 1
LEFT JOIN Servers_2 S2 ON S.id = S2.Server_Id AND S.Game = 2
Instead of using CASE, you could probably just use COALESCE as each Id/Game should be unique and only 1 wouldn't be NULL:
SELECT COALESCE(S1.game_version,S2.game_version,...) game_version
If there is no way the same server id can be in multiple tables, then you can leave the AND S.Game... out of the LEFT JOINs as it wouldn't longer be needed. Depends on your unique keys.
Alternatively, you could use Dynamic SQL.

How to group result in the same line : Many to Many relationship by using MySQL

I have 2 tables join by Many-to-Many relationship, I create the 3rd table, and I have a query like this one :
SELECT product.product_name, provider.provider_name
FROM product, provider, provider_product
WHERE product.id_product = provider_product.ref_product
AND provider.id_provider = provider_product.ref_provider
I need to group my result by product_name and the result must be in the same line, like that : if a product have a lot of providers :
my result will be :
product.product_name | provider.provider_name
this is my first product 1 | this is provider1 / this is provider2 / this is provider3
As you see, Providers are in the same line, and they are splitting by /
Use the GROUP_CONCAT() function.
SELECT product.product_name, GROUP_CONCAT(provider.provider_name SEPARATOR '/')
FROM product, provider, provider_product
WHERE product.id_product = provider_product.ref_product
AND provider.id_provider = provider_product.ref_provider
GROUP BY product.product_name

Using 'AND' in SQL WHERE clause for the same filed

Here is the scenario. I have 1 table that has all the contact details. Another table that has all the list of Categories. And a 3rd table which is an associate table, that has the ID of the first table and the ID of the second table.
This is how my associate table looks like
contactdid -2 | categoryid -1
contactdid -2 | categoryid -2
contactdid -2 | categoryid -3
contactdid -3 | categoryid -1
contactdid -3 | categoryid -3
This is my SQL code below(Generated using SQLyog and i included the where clause).
SELECT
press_contacts.email
FROM
contacts_category
INNER JOIN press_category
ON (contacts_category.categoryid = press_category.id)
INNER JOIN press_contacts
ON (contacts_category.contactdid = press_contacts.id)
WHERE contacts_category.categoryid = 1 AND contacts_category.categoryid = 2 ;
I get the output when I do not have AND contacts_category.categoryid = 2inserted in the code.
Any idea how to solve this.I clearly have data.
Thanks in advance for the help.
contacts_category.categoryid can not be 1 and 2 at the same time, perhabs you mean OR instead of AND?
Use OR or IN() instead of AND.
A field can't have two values at the same time
If you only want to see those email addresses with contacts in both categories, try:
SELECT press_contacts.email
FROM contacts_category
INNER JOIN press_contacts
ON (contacts_category.contactdid = press_contacts.id)
WHERE contacts_category.categoryid in (1, 2)
GROUP BY press_contacts.email
HAVING COUNT(DISTINCT contacts_category.categoryid)=2

MySQL - What's wrong with the query?

I am trying to query a database to find the following.
If a customer searches for a hotel in a city between dates A and B, find and return the hotels in which rooms are free between the two dates.
There will be more than one room in each room type (i.e. 5 Rooms in type A, 10 rooms in Type B, etc.) and we have to query the database to find only those hotels in which there is at least one room free in at least one type.
This is my table structure:
**Structure for table 'reservations'**
reservation_id
hotel_id
room_id
customer_id
payment_id
no_of_rooms
check_in_date
check_out_date
reservation_date
**Structure for table 'hotels'**
hotel_id
hotel_name
hotel_description
hotel_address
hotel_location
hotel_country
hotel_city
hotel_type
hotel_stars
hotel_image
hotel_deleted
**Structure for table 'rooms'**
room_id
hotel_id
room_name
max_persons
total_rooms
room_price
room_image
agent_commision
room_facilities
service_tax
vat
city_tax
room_description
room_deleted
And this is my query:
$city_search = '15';
$check_in_date = '29-03-2010';
$check_out_date = '31-03-2010';
$dateFormat_check_in = "DATE_FORMAT('$reservations.check_in_date','%d-%m-%Y')";
$dateFormat_check_out = "DATE_FORMAT('$reservations.check_out_date','%d-%m-%Y')";
$dateCheck = "$dateFormat_check_in >= '$check_in_date' AND $dateFormat_check_out <= '$check_out_date'";
$query = "SELECT $rooms.room_id,
$rooms.room_name,
$rooms.max_persons,
$rooms.room_price,
$hotels.hotel_id,
$hotels.hotel_name,
$hotels.hotel_stars,
$hotels.hotel_type
FROM $hotels,$rooms,$reservations
WHERE $hotels.hotel_city = '$city_search'
AND $hotels.hotel_id = $rooms.hotel_id
AND $hotels.hotel_deleted = '0'
AND $rooms.room_deleted = '0'
AND $rooms.total_rooms - (SELECT SUM($reservations.no_of_rooms) as tot
FROM $reservations
WHERE $dateCheck
GROUP BY $reservations.room_id) > '0'";
The number of rooms already reserved in each room type in each hotel will be stored in the reservations table.
The thing is the query doesn't return any result at all. Even though it should if I calculate it myself manually.
I tried running the sub-query alone and I don't get any result. And I have lost quite some amount of hair trying to de-bug this query from yesterday. What's wrong with this? Or is there a better way to do what I mentioned above?
Edit: Code edited to remove a bug. Thanks to Mark Byers.
Sample Data in reservation table
1 1 1 2 1 3 2010-03-29 2010-03-31 2010-03-17
2 1 2 3 3 8 2010-03-29 2010-03-31 2010-03-18
5 1 1 5 5 4 2010-03-29 2010-03-31 2010-03-12
The sub-query should return
Room ID : 1 Rooms Booked : 7
Room ID : 2 Rooms Booked : 8
But it does not return any value at all.... If i remove the dateCheck condition it returns
Room ID : 2 Rooms Booked : 8
Your problem is here:
$rooms.total_rooms - (SELECT SUM($reservations.no_of_rooms) as tot,
$rooms.room_id as id
FROM $reservations,$rooms
WHERE $dateCheck
GROUP BY $reservations.room_id) > '0'"
You are doing a subtraction total_rooms - (tot, id) where the first operand is a scalar value and the second is a table with two columns. Remove one of the columns in the result set and make sure you only return only one row.
You also should use the JOIN keyword to make joins instead of separating the tables with commas. That way you won't forget to add the join condition.
You probably want something along these lines:
SELECT column1, column2, etc...
FROM $hotels
JOIN $rooms
ON $hotels.hotel_id = $rooms.hotel_id
JOIN (
SELECT SUM($reservations.no_of_rooms) as tot,
$rooms.room_id as id
FROM $reservations
JOIN $rooms
ON ??? /* Aren't you missing something here? */
WHERE $dateCheck
GROUP BY $reservations.room_id
) AS T1
ON T1.id = room_id
WHERE $hotels.hotel_city = '$city_search'
AND $hotels.hotel_deleted = '0'
AND $rooms.room_deleted = '0'
AND $rooms.total_rooms - T1.tot > '0'