Rails ActiveRecord use join or includes instead of find_by_sql to get attributes of two tables - ruby

The following gets me the results I want but I am trying to figure out if I could have done this with a join or includes instead.
#items = Item.find_by_sql("SELECT *
FROM items_with_metadata
FULL OUTER JOIN items ON items.id = items_with_metadata.item_id")
The result should be that I get all attributes from both tables and the attributes are null wherever the items_with_metadata did not match an item in the items table.
ALSO, I do not have any associations between the two tables, the id of some items just happens to be in both tables
So for example if I have
items table with
id | name | active
------------------
123 | a | 0
456 | b | 1
and items_with_metadata has
color | usable | location | item_id
-----------------------------------
red | yes | north | 123
the result of the query will be
id | name | active | color | usable | location | item_id
--------------------------------------------------------
123 | a | 0 | red | yes | north | 123
456 | b | 1 | | | |
I was hoping there was a way to do this using ActiveRecord's joins or includes or any other ActiveRecord method that is not find_by_sql

How about:
Item.joins('FULL OUTER JOIN items_with_metadata ON items.id = items_with_metadata.item_id')
EDIT:
You could also use:
#items = Item.includes(:items_with_metadata)
This will return only Item models, but will also load all relevant ItemWithMetadata models to the memory which will make them available via:
#items.first.items_with_metadata
The last statement won't cause a DB query, but load the item metadata from the memory.

Related

TABLE ACCESS FULL in Oracle execution plan

I have been tasked to find out the SELECT statement for an explain plan
------------------------------------------
| Id | Operation | Name |
------------------------------------------
| 0 | SELECT STATEMENT | |
| 1 | HASH JOIN RIGHT ANTI | |
| 2 | VIEW | VW_NSO_1 |
| 3 | HASH JOIN RIGHT SEMI| |
| 4 | TABLE ACCESS FULL | PART |
| 5 | TABLE ACCESS FULL | ORDERS |
| 6 | TABLE ACCESS FULL | CUSTOMER |
------------------------------------------
I am able to find the select statement from Id 0-5 but what does the line 6 mean?
This is what I have managed to figure out so far I can't get where the last sentence comes into play.
select *
from customer c join orders o
on c.custkey = o.custkey
where o_totalprice
not in
(select p_retailprice
from part p join orders o
on orders.o_custkey >= 0 and 0.1*o_totalprice >= 0)
I can't get where the last sentence comes into play?
Your query is:
select *
from customer c join orders o
on c.custkey = o.custkey
where o_totalprice
not in
(select p_retailprice
from part p join orders o
on orders.o_custkey >= 0 and 0.1*o_totalprice >= 0)
And your explain plan is
------------------------------------------
| Id | Operation | Name |
------------------------------------------
| 0 | SELECT STATEMENT | |
| 1 | HASH JOIN RIGHT ANTI | |
| 2 | VIEW | VW_NSO_1 |
| 3 | HASH JOIN RIGHT SEMI| |
| 4 | TABLE ACCESS FULL | PART |
| 5 | TABLE ACCESS FULL | ORDERS |
| 6 | TABLE ACCESS FULL | CUSTOMER |
------------------------------------------
In your case, this is what happens:
You are getting all the records from both customer and orders that match the condition based on the custkey field.
Your predicate information is delimiting the output to those where o_totalprice ( by the way it should clarified for reading easiness where this field is coming from, although I guess is from orders table ) is not part of the dataset retrieved from the subquery.
the subquery is getting all values of p_retailprice that match the join between part and orders using orders.o_custkey >= 0 and 0.1*o_totalprice >= 0
Getting this in consideration the CBO is:
Accessing ( Line 6 ) by TABLE FULL SCAN the table CUSTOMER, which is logical as you are getting all fields from the table and probably you have no index over custkey.
Making a HASH SEMI JOIN ( line 3 ) between PARTS and ORDERS. In general, a semi join is used for an in or exists clause, and the join stops as soon as the exists condition or the in condition is satisfied.
The HASH JOIN ANTI of line 1 is when the optimizer push the join predicate into a view, normally when an anti join ( not in ) is in place. This is then join to the CUSTOMER TABLE in line 6.
You are filtering only in the right table of the join ( ORDERS ) that is why the access are reflecting that.
This is just an overview of your execution plan and the reasons why the CBO is using those access paths.

MySQL - Top 5 rank best seller plans or courses

I sell subscriptions of my online course, as well as the courses in retail.
I would bring the "top 5" of best selling plans / courses. For this, I have a table called "subscriptionPlan", which stores the purchased plan ID, or in the case of a course, the course ID, and the amount spent on this transaction. Example:
table subscriptionPlan
sbpId | subId | plaId | couId | sbpAmount
1 | 1 | 1 | 1 | 499.99
2 | 2 | 1 | 2 | 499.99
3 | 3 | 2 | 0 | 899.99
4 | 4 | 1 | 1 | 499.99
Just for educational purposes, plaId = 1 is a plan called "Single Sale" that I created, to maintain the integrity of the DB. When the couId isn't empty, you also have bought a separate course, not a plan where you can attend any course.
My need is: List the top 5 sales. If it is a plan, display the plan name (plan table, column plaTitle). If it is a course, display its name (table course, colna couTitle). This logic that I can't code. I was able to rank a top 5 of PLANS, but it groups the courses, since the GROUP BY is by the ID of the plan. I believe the prank is here, maybe creating an IF / ELSE in this GROUPBY, but I don't know how to do this.
The query that i code, to rank my top 5 plans is:
SELECT sp.plaId, sp.couId, p.plaTitle, p.plaPermanent, c.couTitle, SUM(sbpAmount) AS sbpTotalAmount
FROM subscriptionPlan sp
LEFT JOIN plan p ON sp.plaId = p.plaId
LEFT JOIN course c ON sp.couId = c.couId
GROUP BY sp.plaId
ORDER BY sbpTotalAmount DESC
LIMIT 5
The result that i expected was:
plaId | couId | plaTitle | couTitle | plaPermanent | sbpTotalAmount
1 | 1 | Venda avulsa | Curso 01 | true | 999.98
2 | 0 | Acesso total | null | false | 899.99
3 | 2 | Venda avulsa | Curso 02 | true | 499.99
How could I get into this query formula?
When grouping you can use:
Simple columns, or
Any [complex] expression.
In your case, it seems you need to group by an expression, such as:
GROUP BY CASE WHEN sp.plaId = 1 THEN -1 ELSE sp.couId END
In this case I chose -1 as the grouping for the "Single Plan". You can replace the value for any other that doesn't match any couId.

How to repeat query in Oracle Forms upon dynamically changing ORDER_BY clause?

I have an Oracle Forms 6i form with a data block that consists of several columns.
------------------------------------------------------------------------------
| FIRST_NAME | LAST_NAME | DEPARTMENT | BIRTH_DATE | JOIN_DATE | RETIRE_DATE |
------------------------------------------------------------------------------
| | | | | | |
| | | | | | |
| | | | | | |
| | | | | | |
------------------------------------------------------------------------------
The user can press F7 (to Enter in Query Mode, for example, he/she types JOH% in the first_name and H% in the DEPARTMENT field) , then F8 to execute the query and see the results. In this example, a list of all employees with their last name starting with JOH and working in any department starting with H will be listed. Here is a sample output of that query
------------------------------------------------------------------------------
| FIRST_NAME | LAST_NAME | DEPARTMENT | BIRTH_DATE | JOIN_DATE | RETIRE_DATE |
------------------------------------------------------------------------------
| MIKE | JOHN | HUMAN RES. | 05-MAY-82 | 02-FEB-95 | |
| BEN | JOHNATHAN | HOUSING | 23-APR-76 | 16-AUG-98 | |
| SMITH | JOHN | HOUSING | 11-DEC-78 | 30-JUL-91 | |
| | | | | | |
------------------------------------------------------------------------------
I then added a small button on top of each column to allow the user to sort the data by the desired column, by executing WHEN-BUTTON-PRESSED trigger:
set_block_property('dept', order_by, 'first_name desc');
The good news is that the ORDER_BY does change. The bad news is that the user never notice the change because he/she will need to do another query and execute to see the output ordered by the column they selected. In other words, user will only notice the change in the next query he/she will execute.
I tried to automatically execute the query upon changing the ORDER_BY clause like this:
set_block_property('dept', order_by, 'first_name desc');
go_block('EMPLOYEE');
do_key('EXECUTE_QUERY');
/* EXECUTE_QUERY -- same thing */
but what happens is that all data from the table is selected, ignoring the criteria that the user has initially set during the query mode entry.
I also searched for a solution to this problem and most of them deal with SYSTEM.LAST_QUERY and default_where. The problem is, last_query can refer to a different block from a different form, that is not valid on the currently displayed data bloc.
How can do the following in just one button press:
1- Change the ORDER_BY clause of the currently active datablock
and: 2- Execute the last query that the user has executed, using the same criteria that was set?
Any help will be highly appreciated.
You can get the last query of the block with get_block_property built-in function:
GET_BLOCK_PROPERTY('EMPLOYEE', LAST_QUERY);
Another option is to provide separate search field(s) on the form, instead of using the QBE functionality.

How are product attributes and attribute options stored in Magento database?

I am trying to figure out how the linkage between attribute and attribute options, and product and attributes are made in Magento. Is there any reference to how this is working? or anyone give me a hint on this.
Thanks,
Balan
As Alan Storm says: "you do not have to know about how your db works. You have to learn how the models work ". (This is not an exact quote. I gave you the meaning).
But I created own scheme to understand the DB structure. So this screen shows how it works:
Hope, it helps.
Also I recommend you to look through these links:
http://www.magentocommerce.com/wiki/2_-_magento_concepts_and_architecture/magento_database_diagram
http://alanstorm.com/magento_advanced_orm_entity_attribute_value_part_1
1) The attributes are stored in eav_attribute. There you get the attribute_id.
2) The options are stored in eav_attribute_option_value. There yout get the option_id.
3) The options are assigned to the product in catalog_product_entity_varchar. There you need the entity_id of the product, the attribute_id from 1) and the value which are the comma separated option_ids from 2)
I've found these queries to be very helpful for hunting down things like - where does it say the product color is black?, for example.
-- show_product_attr.sql
select
p.entity_id,
p.entity_type_id,
p.attribute_set_id,
p.type_id,
p.sku,
a.attribute_id,
a.frontend_label as attribute,
av.value
from
catalog_product_entity p
left join catalog_product_entity_{datatype} av on
p.entity_id = av.entity_id
left join eav_attribute a on
av.attribute_id = a.attribute_id
where
-- p.entity_id = 28683
-- p.sku = '0452MR'
p.entity_id = {eid}
;
And for attr_options
-- show_product_attr_options.sql
select
p.entity_id,
-- p.entity_type_id,
-- p.attribute_set_id,
p.type_id,
p.sku,
a.attribute_id,
a.frontend_label as attribute,
-- a.attribute_code,
av.value,
ao.*
from
catalog_product_entity p
left join catalog_product_entity_int av on
p.entity_id = av.entity_id
left join eav_attribute a on
av.attribute_id = a.attribute_id
left join eav_attribute_option_value ao on
av.value = ao.option_id
where
-- p.entity_id = 28683
p.entity_id = {eid}
;
You need to replace {datatype} with text, varchar, int, decimal, etc, for the first query, and {eid} with entity_id for both queries. Which you can do on the command like like this:
$ cat show_product_attr_options.sql | sed -e "s/{eid}/30445/" | mysql -uUSER -pPASS DATABASE -t
+-----------+---------+--------------+--------------+---------------------------+-------+----------+-----------+----------+--------------------+-------------+
| entity_id | type_id | sku | attribute_id | attribute | value | value_id | option_id | store_id | value | colorswatch |
+-----------+---------+--------------+--------------+---------------------------+-------+----------+-----------+----------+--------------------+-------------+
| 30445 | simple | 840001179127 | 96 | Status | 1 | 5972 | 1 | 0 | Male | NULL |
| 30445 | simple | 840001179127 | 102 | Visibility | 1 | 5972 | 1 | 0 | Male | NULL |
| 30445 | simple | 840001179127 | 122 | Tax Class | 2 | 5973 | 2 | 0 | Female | NULL |
| 30445 | simple | 840001179127 | 217 | Size | 257 | 17655 | 257 | 0 | XS | NULL |
| 30445 | simple | 840001179127 | 217 | Size | 257 | 17657 | 257 | 1 | XS | NULL |
| 30445 | simple | 840001179127 | 224 | Color | 609 | 18717 | 609 | 0 | Arctic Ice Heather | NULL |
| 30445 | simple | 840001179127 | 260 | Featured | 0 | NULL | NULL | NULL | NULL | NULL |
| 30445 | simple | 840001179127 | 262 | Clearance Product | 0 | NULL | NULL | NULL | NULL | NULL |
| 30445 | simple | 840001179127 | 263 | Skip from Being Submitted | 0 | NULL | NULL | NULL | NULL | NULL |
| 30445 | simple | 840001179127 | 283 | Discontinued | 0 | NULL | NULL | NULL | NULL | NULL |
+-----------+---------+--------------+--------------+---------------------------+-------+----------+-----------+----------+--------------------+-------------+
A similar set of sql scripts can be created for catalog.
Product Attributes are extra values that you can assign to a product and is stored in the main EAV table, by name, and the data is then stored in a few different tables based on the data type, like varchar, decimal, text Integer, date, etc.
if you had multiple values for your Product Attribute, then that will be stored in the Attribute Options tables, again, different tables based on the data type.
the following link explains the relationships better:
http://www.magentocommerce.com/wiki/2_-_magento_concepts_and_architecture/magento_database_diagram
And deeper developer's detail:
http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-7-advanced-orm-entity-attribute-value
And Attribute sets will be the other thing you come across, like the name suggests, a set of attributes grouped together. http://www.magentocommerce.com/knowledge-base/entry/how-do-i-create-an-attribute-set
HTH
Shaun
SELECT pei.value
FROM `catalog_product_entity_int` pei
JOIN `eav_attribute` ea
ON pei.attribute_id = ea .attribute_id
WHERE pei.entity_id = {your product_id}
AND ea.attribute_code = '{your attribute_code}'
Note that there are a number of different tables like catalog_product_entity_int depending on the type of the attribute, so one of those other ones could be appropriate.
You can get all product properties by using this query:
SELECT CPEV.entity_id, CPE.sku, EA.attribute_id, EA.frontend_label, CPEV.value
FROM catalog_product_entity_varchar AS CPEV
INNER JOIN catalog_product_entity AS CPE ON CPE.entity_id = CPEV.entity_id
INNER JOIN eav_attribute AS EA ON(CPEV.attribute_id = EA.attribute_id AND EA.entity_type_id = 4)
INNER JOIN catalog_eav_attribute AS CEA ON(CEA.attribute_id = EA.attribute_id AND CEA.is_visible_on_front = 1 AND CEA.is_visible_in_grid = 1)

DataMapper associates that depend on two columns

I have a table of products with attributes like SKU, Name, etc.
It seems like I need to have separate tables for each category of product due to the large variety of features depending on the category.
Say I have a table/class for boots, tools and hats
I'd like (unless there's a better way) to join/associate my products table to the other tables where appropriate (depending on category)?
Products Table
id | Name | SKU | Category(Table) | CategoryTableForeignKey
----------------------------------------------------------------------
1 | boot1 | 123 | Boots | 2
2 | knife1 | 345 | Tools | 42
-
Boots Table
id | product_id | Size | Width | Color | Sex
----------------------------------------------------------------------
2 | 1 | 9.5 | Wide | Olive | Male
-
Tools Table
id | product_id | length | Fixed | Coating | Etc
----------------------------------------------------------------------
42 | 2 | 4.5 | False | ... | ...
I'm not sure how to do this with DataMapper classes.
Ideally, I'd like to be able to:
my_boot = Boots.get(1)
my_boot.product.sku
Edit: dkubb pointed out a flaw in my code.
When you use has() what you're saying is that the foreign key is in the other model. If you want the foreign key to be in the table associated with the current model you want to use belongs_to.
class Product
include DataMapper::Resource
#descripe product properties ...
has n, :boots
end
Class Boot
include DataMapper::Resource
#describe boot properties ...
belongs_to :product
end
About DataMapper Associations: http://datamapper.org/docs/associations.html

Resources