MySQL Create View from 2 different tables and columns - mysql

I am trying to create a view of 2 tables.
Currently, I am using the line below and this works fine, but I am getting too much information back, I need to be more selective and choose columns:
first table
wp_cart66_orders and i need to pull
bill_first_name_, bill_last_name
status=, new or shipped etc...
2nd table
wp_cart_66_order_items
description, quantity
I am not sure if I need to create a view or just use this query.
Also, I might need to be pointed in the right direction on how to create it if that is the case.
select wp_cart66_orders.*, wp_cart66_order_items.*
from wp_cart66_orders, wp_cart66_order_items
where wp_cart66_orders.id=wp_cart66_order_items.order_id
and wp_cart66_orders.status = 'new';
Thanks.

Write your selective columns, your join explicitly, and reanme the common column names from two tables.
create view OrderItemsVW
as
select wp_cart66_orders.bill_first_name as Bill_First_Name,
wp_cart66_orders.bill_last_name as Bill_Last_Name,
wp_cart66_orders.Description as OrdersDescription,
wp_cart66_order_items.Description as OrderItemsDescription
from wp_cart66_orders
inner join wp_cart66_order_items
on wp_cart66_orders.id=wp_cart66_order_items.order_id
where wp_cart66_orders.status = 'new';

A view will somehow be faster and can be reused. However, you may also just use your select query.
select wp_cart66_orders.*, wp_cart66_order_items.* from wp_cart66_orders, wp_cart66_order_items where wp_cart66_orders.id=wp_cart66_order_items.order_id and wp_cart66_orders.status = 'new';
this will only work if wp_cart66_orders and wp_cart66_order_items have the same columns.

Use the as operator or list every column you want:
Select table1.col1 AS mycolname, table2.col4 AS mycolname2...
or
Select table1.col1,table2.col4 ...

Related

How to sum all elements in an indexed table

I tried to make a query to my database with this structure: Data Base Structure
I did this query:
SELECT partido.acronimoPartido, SUM(votosacta.numVotos) FROM partido, votosacta WHERE votosacta.partido_idpartido=1 AND partido.idpartido=1
This query does work like I want but displays only the SUM of 'votos' for idpartido=1
I want to be able to sum numVotos from 'votosacta' table for each member of my 'partido' table indexed in 'votosacta' but I seem to not be able to get the right sintax.
I tried something like this:
SELECT partido.acronimoPartido, SUM(votosacta.numVotos) FROM partido, votosacta WHERE votosacta.partido_idpartido = partido.idpartido
You need a group by clause:
select p.acronimoPartido,
SUM(v.numVotos)
from partido p
join votosacta v on v.partido_idpartido = p.idpartido
group by p.acronimoPartido
Also, use explicit join syntax instead of old comma based syntax and use aliases to make your queries concise and readable.

Why is this MySQL statement pulling data from both tables on this JOIN?

select * from user_levels
join collectors_users on user_levels.id = collectors_users.user_level
where collectors_users.username = 'testuser'
I want it to pull everything from user_levels and nothing from collectors_users. But it's pulling from both. How do I correct the statement?
Instead of select * specify what you actually want and use select user_levels.* or even better skip the * and write out the columns you want (and consider using aliases to keep it short and tidy): select ul.col1, ul.col2 ... from userlevels ul join ...
It is getting all the data as the '*' means 'all' columns. You can limit the columns for just one table by specifying the table:
select user_levels.*
from user_levels
join collectors_users on user_levels.id = collectors_users.user_level
where collectors_users.username = 'testuser'
Pro tip: Don't use SELECT * in running software. Instead, be as specific as you can be about the columns you want in your result set.
SELECT user_levels.*
should help a bit.
I might suggest that you use in or exists, because this is more consistent with the intention of the query:
select ul.*
from user_levels ul
where ul.id in (select cu.user_level
from collectors_users cu
where cu.username = 'testuser'
);
In addition, this version will not produce duplicate rows if collectors_users has multiple matching rows for a singel row in user_levels.
Also note the use of table aliases: these make the query easier to write and to read.

MySQL Locate Duplicates between two table with similar column

Using this question's answer. I'm trying to find duplicate records between two tables by the column names matrix_unique_id and Matrix_Unique_ID in each table and then display the full address. The Full address columns are formatted differently from each other in each table so I cannot use that as a comparison. I'm getting an "unknown column fort_property_res.matrix_unique_id" error but everything looks okay?
So two questions:
Will this query find duplicates correctly?
Why the unknown column error?
SQL query:
SELECT matrix_unique_id, full_address
FROM fort_property_res
INNER JOIN (
SELECT Matrix_Unique_ID, FullAddress
FROM sunshinemls_property_res
GROUP BY FullAddress
HAVING count(fort_property_res.matrix_unique_id) > 1
) dup ON fort_property_res.matrix_unique = sunshinemls_property_res.Matrix_Unique_ID
The solution you're trying to copy is a totally different case. You have two tables and (it looks like) a convenient matrix_unique_id to join on, so this is much easier:
SELECT fort.matrix_unique_id, fort.full_address AS fortAddress, sun.FullAddress AS sunAddress
FROM fort_property_res fort, sunshinemls_property_res sun
WHERE fort.matrix_unique_id = sun.Matrix_Unique_ID

SQL - Case in where clause

I got the following sql question that I that won´t work for me. I know that the last CASE row are wrong but I would like to use a CASE statement like that in my where clause.
Short description of my situation:
I got several companies that got there own material linked to them with "companyID". Each material might be linked to a row in pricelist_entries. If I search for one row in the pricelist_entries table that is linked to many material rows all rows will be returned but I just want to return the one that belongs to the current company (the company that performs the search).
Conclusion: If materialID NOT NULL THEN materials.company="current.companyID".
SELECT peID, peName, materialID
FROM pricelist_entries
INNER JOIN pricelist ON pricelist_entries.peParentID=pricelist.pID
LEFT JOIN materials ON pricelist_entries.peID=materials.pricelist_entries_id
WHERE peBrand = 'Kama' AND pricelist.pCurrent = 1
AND (peName LIKE '%gocamp de%' OR peArtnr LIKE '%gocamp de%')
AND pricelist.country=0 AND pricelist_entries.peDeleted=0
CASE materialID WHEN IS NOT NULL THEN materials.companyID=10 END
Please tell me if I need to describe my problem in a better way.
Thanks in advance!
Sounds like just moving the condition into the join would make it simpler;
SELECT peID, peName, materialID
FROM pricelist_entries
INNER JOIN pricelist
ON pricelist_entries.peParentID=pricelist.pID
LEFT JOIN materials
ON pricelist_entries.peID=materials.pricelist_entries_id
AND materials.companyID=10 -- << condition
WHERE peBrand = 'Kama' AND pricelist.pCurrent = 1
AND (peName LIKE '%gocamp de%' OR peArtnr LIKE '%gocamp de%')
AND pricelist.country=0 AND pricelist_entries.peDeleted=0
It will only left join in material rows that are linked to the correct company.
You can't use CASE in the where clause that I'm aware of, you need to use it in the SELECT portion, but it will have the same effect. Something like this should work:
SELECT CASE materialid WHEN IS NOT NULL THEN companyid END as thiscompanyid
This will give you a new column named thiscompanyid and you can query off of that to get what you need.

combining two select statements to return one result

I need to combine the results for two select queries from two view tables, from which I am performing calculations. Perhaps there is an easier way to perform a query using if...else - any pointers?
Essentially I need to divide everything by 'ar.time_ratio' under the condition in sql query 1, and ignore that for query 2.
SELECT
gs.traffic_date,
gs.domain_group,
gs.clicks/ar.time_ratio as 'Scaled_clicks',
gs.visitors/ar.time_ratio as 'scaled_visitors',
gs.revenue/ar.time_ratio as 'scaled_revenue',
(gs.revenue/gs.clicks)/ar.time_ratio as 'scaled_average_cpc',
(gs.clicks)/(gs.visitors)/ar.time_ratio as 'scaled_ctr',
gs.average_rpm/ar.time_ratio as 'scaled_rpm',
(((gs.revenue)/(gs.visitors))/ar.time_ratio)*1000 as "Ecpm"
FROM
group_stats gs,
v_active_ratio ar
WHERE ar.group_id=gs.domain_group
and
SELECT
gs.traffic_date,
gs.domain_group,
gs.clicks,
gs.visitors,
gs.revenue,
(gs.revenue/gs.clicks) as 'average_cpc',
(gs.clicks)/(gs.visitors) as 'average_ctr',
gs.average_rpm,
((gs.revenue)/(gs.visitors))*1000 as "Ecpm"
FROM
group_stats gs,
v_active_ratio ar
where not ar.group_id=gs.domain_group
Use the UNION operator. You can add another column to show which query a row came from if that's important to you.
http://dev.mysql.com/doc/refman/5.1/en/union.html
That's usually what UNION [ALL] is for.
The UNION suggested above will give you all scaled results, and all the non-scaled data (the second query) as separate rows.
If you want to group them on their common data, so you have the scaled and normal data side by side on the same row, you can use a query like this:
SELECT * FROM ( [first-query] ) AS scaled
INNER JOIN ( [second-query] ) AS normal
ON scaled.traffic_date=normal.traffic_date
AND scaled.domain_group=normal.domain_group
Instead of using * to select all columns, may want to explicitly declare the columns selected, since the columns traffice_date and domain_group will be output twice.